Google Interview Question for Front-end Software Engineers






Comment hidden because of low score. Click to expand.
2
of 2 vote

JS solution (makes sense for a Frontend Position)

var inp=[1,2,4,4,6,5,3,3,7,7,7,9,1];
var map = {};
var out = inp.filter(function(data,index,array){
  if(typeof map[data] == 'undefined'){
    map[data]=true;
    return true;
  }else return false;
});

- Aditya October 02, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

typeof map[data] == 'undefined'

may not be a good choice, consider the case, the array contains strings and the string happened to be named as 'toString' etc.

- Anonymous January 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is extra space allowed
If yes then BST will be the best bet....
Time complexity : O(nlogn)

- ibnipun10 August 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. We can use Hashing here is space is not the constraint. O(n)
2. If space is the constrain the we can take the BST and in this we search for the new number if it is in BST the we return else we create new node for new number.

- Ravikant August 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. We can use Hashing here is space is not the constraint. O(n)
2. If space is the constrain the we can take the BST and in this we search for the new number if it is in BST the we return else we create new node for new number. O(nlogn)

- Ravikant August 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hash will work.
Another way is to sort the numbers using any O(nlogn) time algorithm and then do a linear scan.

- ftfish August 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can use the array itself as a Min Heap which has root as the minimum element. Start from item 1 to n of the given array and keep inserting in the min heap. During insertion if we find the item already present then we dont insert and continue with next item. This Min Heap will be created as an almost complete binary tree in-place in the given array itself.
So this will be in-place O(nlogn) approach.

The way suggested by @fitish is also in place but will require an extra O(n) scan after the sort.

Please comment if you have any.

- souravsain August 15, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Heap is not a data structure to search.
So "During insertion if we find the item already present then we dont insert and continue with next item" is incorrect.

- D August 16, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Interviewer did give any constraints concerning space, so my solution was to create an 'output' array, loop through the original and keep track of whether a value had been seen before using a hash. If not, push it onto the output array.

- bjh August 16, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think this and some similar problems are related to Element Distinctness problem (EDP). One can see : "Element Discreteness Problem" in wiki.

So the algo may be:

Sort ascending array to make it partially ordered
i = 0;
if (array[i] - array[++i])
put those into output array
print out output array

- pradip August 18, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a[]=integer input array. n is size of a[].
short lookup[MAX_INT_VAL]={0}; //initialize all to false.
int top=0;
for(int i=0;i<n;i++)
{
if(lookup[a[i]]==0)
{
lookup[a[i]]=1;
a[top++]=a[i];
}
}
n=top;

now i guess we have the same array with all the duplicates removed

- Anonymous August 18, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Why isnt anyone using a HashSet or any Set implementation.
The algo is:
for every integer in inputarray
{
if (!integerset.add)
{
duplicate detected, scrap it
}
}
return integerset

this is main example for Set interface in java doc...
please comment on my thoughts..

- vsp August 19, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Here O(n) time and O(1) space solution of the problem
comments appreciated

#include <algorithm>
#include <iostream>

using namespace std;

#define FOR(i,a,b) for(int i=(a);i<=(b);++i)

#define DBAR(arr,a,b) cout<<#arr<<" : ";FOR(dbar,a,b) cerr<<arr[dbar]<<" ";cerr<<endl;


/*======================================Templates Ends========================*/
/* Main Code Starts from here */

#define N 22

int main (int argc, char const* argv[])
{
int arr[N] = {1,2,2,3,3,3,4,4,5,6,7,7,7,8,8,6,10,10,11,11,23,23};
int k =0;

FOR(i,1,N-1) {
DBAR(arr,0,N-1);
if(arr[i]>arr[k]&& k+1==i) {
k++;
}
else {
while(arr[i]<=arr[k])i++;
//DB(arr[i]);
if(i<N)
swap(arr[++k],arr[i]);
}
}
DBAR(arr,0,N-1);
return 0;
}

- Jiendra August 30, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Of course it's O(n), you're working on an already sorted array. The original problem doesn't have a sorted array to begin with!

- Anonymous August 30, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

It can be done in O(n) using hashmap, and also if we create BST by ignoring creation of nodes with duplicate nodes. I tried to program in Java, source code below:

BSTNode.java:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package careercup.google;

/**
*
* @author Harit
*/
public class BSTNode {
private int value;
private int leftChild;
private int rightChild;

public BSTNode(int v){
value = v;
leftChild = -1;
rightChild = -1;
}

public int getValue(){
return this.value;
}

public int getChild(boolean left){
if(left){
return this.leftChild;
}
else{
return this.rightChild;
}
}
public void setChild(int child, boolean left){
if(left){
this.leftChild = child;
}else{
this.rightChild = child;
}
}
}

RemDupArrayBST:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package careercup.google;

import java.util.ArrayList;

/**
*
* @author Harit
*/
public class RemDupArrayBST {
/* Output Array of Nodes */
private static ArrayList<BSTNode> nodes = new ArrayList<BSTNode>();
private static int parent = -1;
private static boolean left = false;

public static void main(String args[]){
/* Sample Input Array */
//int[] input_array = new int[]{3,1,2,1};
//int[] input_array = new int[]{3,5,4,2,1,2,3,1};
int[] input_array = new int[]{1,2,3,2,4,4};
/* end sample input */

for(int i=0; i<input_array.length; i++){
if(nodes.size() == 0){
/* tree is empty, add root */
BSTNode node = new BSTNode(input_array[i]);
nodes.add(node);
}else{
/* search if node already exists */
if(!contains(input_array[i])){
BSTNode node = new BSTNode(input_array[i]);
nodes.add(node);
nodes.get(parent).setChild(nodes.size()-1, left);
}else{
System.out.println(input_array[i] + " : already exists - ignoring");
}
}
}

/* final print */
System.out.print("Inorder Traversal: ");
inOrderTraverse(nodes.get(0));

System.out.println("");

System.out.print("PostOrder Traversal: ");
postOrderTraverse(nodes.get(0));

System.out.println("");

System.out.print("PreOrder Traversal: ");
preOrderTraverse(nodes.get(0));

System.out.println("");
}

private static boolean contains(int value){
int index = 0;
while(index >= 0){
if (nodes.get(index).getValue() == value){
return true;
}
if (nodes.get(index).getValue() > value){
parent = index;
left = true;
index = nodes.get(index).getChild(true);
}else{
parent = index;
left = false;
index = nodes.get(index).getChild(false);
}
}
return false;
}

private static void inOrderTraverse(BSTNode node){
if(node == null){
return;
}
if(node.getChild(true) != -1){
inOrderTraverse(nodes.get(node.getChild(true)));
}
System.out.print(node.getValue() + " ");
if(node.getChild(false) != -1){
inOrderTraverse(nodes.get(node.getChild(false)));
}
}

private static void postOrderTraverse(BSTNode node){
if(node == null){
return;
}
if(node.getChild(true) != -1){
postOrderTraverse(nodes.get(node.getChild(true)));
}
if(node.getChild(false) != -1){
postOrderTraverse(nodes.get(node.getChild(false)));
}
System.out.print(node.getValue() + " ");
}

private static void preOrderTraverse(BSTNode node){
if(node == null){
return;
}
System.out.print(node.getValue() + " ");
if(node.getChild(true) != -1){
preOrderTraverse(nodes.get(node.getChild(true)));
}
if(node.getChild(false) != -1){
preOrderTraverse(nodes.get(node.getChild(false)));
}
}
}

- daydreamer August 31, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Remeber, they want you to write all your code on the whiteboard... I think you might need several whiteboards for all that!

- bjh September 10, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@bjh
what exactly do you mean? do we need not write exact code

- Anonymous September 10, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I mean that during the interviews Google requires you to write complete and valid source code on the whiteboard. The above solution, while it probably works, is much too large for that. Probably a good indicator that there is a much simpler solution, which there is and others have posted.

- bjh September 10, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def remove_dups(A):
  uniq_set = set()
  uniq_list = []
  for a in A:
    if a not in uniq_set:
      uniq_set.add(a)
      uniq_list.append(a)
  return uniq_list

- Bullocks September 06, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Array in question is already seems sorted.
int i=1;
int j=0;
while(i<n)
{
while(a[i++] == a[j]);
a[j++] = a[i++];
}
a[0..j] will have required elements.

- Anonymous September 06, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

1,2,3,2,4,4 is already sorted? Dude ...

- Bullocks September 07, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

JS solution (makes sense for a Frontend Position)

var inp=[1,2,4,4,6,5,3,3,7,7,7,9,1];
var map = {};
var out = inp.filter(function(data,index,array){
  if(typeof map[data] == 'undefined'){
    map[data]=true;
    return true;
  }else return false;
});

- NetRoY October 02, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Simple Javascript solution

var a = [1,2,4,6,3,4,4,3,2,2,7,3,6,8];
var removeDup = function(){
	for(i=0;i<a.length;){//IMPORTANT LINE
		if(a[i-1] ==a[i]){
			a.splice(i,1);
		}
		else{
			i++;
		}
	}
	return a;
}
document.writeln(removeDup());

- Vinod February 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is not going to work for non contiguous duplicates.

- Anonymous October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

if(typeof(Array.prototype.rmDuplicate)==='undefined'){
    Array.prototype.rmDuplicate = function(){
         var arr = [],
             input = this;
         this.forEach(function(v,i){
             if(arr.indexOf(v)===-1){
                arr.push(v);
             }
         })
       return arr;
      }
    }
         
     var array = [1,2,3,3,3];
     document.write(array.rmDuplicate());

- zhujy8833 December 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is in Javascript:

a = [1,2,3,2,4,4];
var out = [];
a.filter(function(item){
  if(out.indexOf(item) === -1){
      out.push(item);  
  }
}); 
a = out;
console.info(a);

- Leonardo Correa March 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JS solution similar to one that has been written

function sortArray(array){
		var newArray = [];
		for(var i=0; i<array.length; i++){
			if( newArray.indexOf(array[i]) == -1 ){
				newArray.push(array[i]);
			}
		}
		return newArray;
	}

- Dxn7335 August 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var res = [];
      var len = arr.length;
      // Start timing now
      for(var i = 0; i < len; i++) {
        if(res.indexOf(arr[i]) == -1) {
          res.push(arr[i])
        }
      }

This has a running time of O(n) which is not bad..

- This is simple October 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is not O(n). It is O(n2). You forgot to count res.indexOf()

- aduyng December 18, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

[1, 2, 3, 2, 1, 3, 4, 5].reduce(function(prev, current) {
        (prev.indexOf(current) < 0) && prev.push(current);
        return prev;
    }, []);

- kronung January 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function removeDuplicates(elements){
var map = {};
for(var i = 0; i < elements.length; i++){
map[elements[i]] = true;
}
var result = [];
for(var j in map ){
result.push(parseInt(j, 10));
}

return result;
}

console.log(removeDuplicates([1,2,4,4,6,5,3,3,7,7,7,9,1]));

- aduyng December 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Array.prototype.removeDuplicates = function () {
  return this.filter((element,index, array) => array.slice(0, index).indexOf(element) === -1);
}
[1,2,3,4,1,3,5,2,6].removeDuplicates(); // [1, 2, 3, 4, 5, 6]

- Fernando March 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript:

let sourceArray = [1,2,3,2,4,4];
let removeDuplicates = array => {
	let targetArray = [];
  
	array.map(number => {
    if(!targetArray.includes(number)){
      targetArray.push(number);
    }
  });

  console.log(targetArray);
};

removeDuplicates(sourceArray);

- hodgef December 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function removeDuplicates(list){
  const numbers = new Set();
  let clean = [];
  for (let i=0;i<list.length; i++){
    if (!numbers.has(list[i])){
      clean.push(list[i]);
      numbers.add(list[i]);
    }
  }
  return clean;
}

console.log(removeDuplicates([1,2,3,2,4,4]));

- Aiman October 09, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More