Google Interview Question for Software Engineer / Developers


Country: India
Interview Type: Phone Interview




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

Have an array and a map of (int,int).

Insert(n)
{
Add to end of array if not already there in map
update map with key => n and value = index in array.
}

Remove(n)
{
Find n from map index=i
Remove n from map.
Swap i and last element in array.
update last element and its new index in map.
}

GetRandomElement()
{
Generate a random number between 0 and size of array.
Return the element at the corresponding index.
}


If you choose the map to hash, all operations are o(1).
If you choose the map to be a binary tree, Insert/Remove are O(logn)

- Anonymous October 28, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You assumed a lot of things.

- This doesn't allow for duplicates, when this was no where mentioned
- You are using almost double space than is required
- In Remove you are changing the order of the elements, which you shouldn;t be doing ideally.


In my assumtion:
It should be a simple Array,
where Insert and GetRandomElement are O(1), and Remove is O(n)

- Anonymous October 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

good job....google will hire you in a snap

- Anonymous October 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Second anonymous.. That is the most retarded thing I have ever heard. A binary tree storing ints will typically take three times as much storage. One for ( int , ptr to left and ptr to right ) on each node. By your logic one should always stick to arrays because you are using more storage then needed.

Replace map with multimap and you can handle duplicates.

- Anonymous October 29, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If ordering of elements is not important, this could be one solution.

Using hashmap can provide the following solution:

insert(n):
hash n to an index i and add an entry in O(1)
duplicates can be handled by appending to linked list pointed by an index

remove(n):
hashing n to index i, and removing its entry from linked list pointed to by an index i

getRandomElement():
Get the size of keys and generate random element between 1 and size of keys. Iterate to the key, value pairs from random element index until some non-null entry is found.

- spiderman July 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This is not O(1) for insertion & deletion. Map takes O(logN) operation to search insert & delete

- avinash October 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

implement using an array and a HashMap that handle dupliates

ideone.com/rlrIuy

class RandomMap
{
        private int size;
        private int[] a;
        private Map<Integer, List<Integer>> map;
        private Random r;
 
        public RandomMap(int capacity)
        {
                size = 0;
                a = new int[capacity];
                map = new HashMap<Integer, List<Integer>>();
                r = new Random();
        }
 
        public int size()
        {
                return size;
        }
 
        // TODO: resize
        public void add(int n)
        {
                int index = size++;
                a[index] = n;
                if(map.containsKey(n)) map.get(n).add(index);
                else {
                        List<Integer> l = new ArrayList<Integer>();
                        l.add(index);
                        map.put(n, l);
                }
        }
 
        public void remove(int n)
        {
                if(map.containsKey(n)) {
                        int p = map.get(n).get(0);
                        map.get(n).remove(0);
                        if(p != size - 1) {
                                int m = a[size - 1];
                                a[p] = m;
                                List<Integer> l2 = map.get(m);
                                for(int i = 0; i < l2.size(); i++) {
                                        if(l2.get(i) == size - 1) {
                                                l2.set(i, p);
                                                break;
                                        }
                                }
                        }
                        size--;
                }
        }                                   
        
        public int getRandom()
        {
                if(size > 1) return a[r.nextInt(size - 1)];
                else if(size == 1) return a[0];
                else throw new NoSuchElementException();
        }
}

- dgbfs December 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

I think the problem is intended to test you about the time complexity of operations when you implement it with different data structures: vector, linkedlist, binary tree, heap, set, bins. If you can compare different time complexity, I believe that is what the interviewer has in mind. The best example come from "Programming Pearl 2nd edition Column Search", where the author implements a search structure containing insert, find, size, using the above data structures. And the author compare the time complexity in details

- geliang2008 November 09, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yep, i think so too.
Though he asked me to write production ready code for this. So if you are suggesting a complicated structure, be sure, u can code it too.

- P November 10, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think a simple array would do best here ..

- Anonymous October 29, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what is complexity for Remove(n), insert(n)?

- kamoliddin June 21, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

This just requires a Object which encapsulates a unordered_multiset .

Insertion in O(1), Provided perfect hashing function
Deletion O(1)
Random Number, we have to iterate the set to get the random element . I could not think of any O(1) for this , without using extra Datastructure .

- Balaji October 31, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Guys, it is possible for all three to be O(1) .. ??

- Anonymous October 31, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

the first solution does it

- Anonymous November 06, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can do all 3 with O(logN) using BST. Taking random is Kth element.

- Alex Fetisov December 14, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this could be one of the good if all operations insert, delete and get_random are equally likely.

- spiderman July 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Why not heap (stored as an array)?
insert and delete will take O(logN) and get random number will take O(1) time.
index = rand() % heap_size[A]

- maddy February 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I was asked this question at Amazon. Only difference was to solve this with existing Java APIs. With some difficulty I could solve. Nevertheless they did not hire me :(
I am making an assumptions here. There will not be any hash collisions i.e. hash buckets are large enough.

RandomMap will contain a List and a HashMap. List will contain every element that is inserted. So get random is easy from a list as said in above points.
HashMap can be used to retrieve elements with a get(key) and put(key,value). Problem - value duplication in list and HashMap. Instead value can be index of array element Then List.get(value) will give the real element.
What if there ARE DUPLICATES?? Now there will be hash collosions for sure. get will now have to iterate over the list of collisioned objects. Not O(1)!
So another redirection is used. Instead of the index value in the HashMap we will store another HashMap<Integer,Integer>. First Integer - a running count which is incremented with value addition. Second Integer - Array Index.

public class RandomMap<K, V> 
{
  private List<V> _entryList = new ArrayList<>();
  private Map<K, HashMap<Integer,Integer>> _entryMap = new HashMap<>();
  
  public int size()
  {
    return _entryList.size();
  }
  
  public V get(Object key)
  {
    HashMap<Integer, Integer> randomMap = _entryMap.get(key);
    return _entryList.get( randomMap.get(0) );
  }

  public void put(K key, V value)
  {
    _entryList.add(value);
    HashMap<Integer, Integer> randomMap = _entryMap.get(key);
    if(randomMap == null)
    {
      randomMap = new HashMap<>(); 
    }
    randomMap.put(randomMap.size(), _entryList.size() - 1);
  }

  public void remove(Object key)
  {
    HashMap<Integer, Integer> randomMap = _entryMap.get(key);
    Integer indexToBeRemoved = randomMap.get(0);
    
    int lastIndex = _entryList.size() - 1;
    _entryList.add(indexToBeRemoved, _entryList.get(lastIndex));
    _entryList.remove(lastIndex);
  }

  public V getRandom()
  {
    return _entryList.get(new Random().nextInt(_entryList.size()));
  }
}

This could be further improved if we use one more change. Why? I will leave it to your imagination :)

private Map<K, RandomMap<Integer,Integer>> _entryMap = new HashMap<>();

- JDev September 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 4 vote

This comment has been deleted.

- Administrator November 07, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Really? Think again ...

- P November 07, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Wad d hell ! How did you implement getRandomElement using a Trie. Besides as per my understanding, insert and delete here operates on number, how are you saving them in a trie ? Are you saving their digits along a Trie path ?

- Felix November 07, 2011 | Flag


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