Google Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
Random access doesn't mean get a random element.. Random access means you can get any element no matter where it is in the strucure.. Like in an array you get the ith element with arr[i]. In a linked list you'd have to traverse the list until you get to the ith element..
This question is to general to give the most effective data structure, first we need to ask question like which scenario our data structure is going to be used, is going to be in constant change or is going to be used for search mostly, what about memory requirements (a LL or BST based DS could be more effective), features of the type of objects we are going to store in it.
But based only in the operations described in the question a simple HashMap solve the problem since the order in which the elements are inserted is not important to the rest of the operations, a DS with a re-sizable array solve the problem too since no time complexity was specified.
This is how I would've answered the question in a real interview.
You need to define your desired operational time and space complexity requirements as there are many data structures (all set data structures) that provide these three fundamental of operations. I expect you were either expected to describe the pros and cons of a few and/or probe the interviewer to refine the requirements before jumping into an answer.
We can use hashing to support first 3 operations in Θ(1) time. How to do the 4th operation? The idea is to use a resizable array (ArrayList in Java, vector in C) together with hashing. Resizable arrays support insert in Θ(1) amortized time complexity. To implement getRandom(), we can simply pick a random number from 0 to size-1 (size is number of current elements) and return the element at that index. The hash map stores array values as keys and array indexes as values.
- smarthbehl August 21, 2015Following are detailed operations.
insert(x)
1) Check if x is already present by doing a hash map lookup.
2) If not present, then insert it at the end of the array.
3) Add in hash table also, x is added as key and last array index as index.
remove(x)
1) Check if x is present by doing a hash map lookup.
2) If present, then find its index and remove it from hash map.
3) Swap the last element with this element in array and remove the last element.
Swapping is done because the last element can be removed in O(1) time.
4) Update index of last element in hash map.
getRandom()
1) Generate a random number from 0 to last index.
2) Return the array element at the randomly generated index.
search(x)
Do a lookup for x in hash map.