Google Interview Question
Software Engineer / DevelopersI guess a solution better than O(N) must be obtained using TRIES (prefix trees).
We can arrange all the names and surnames in 2 different tries.
But here also we will require a connection between two tries. Can anybody suggest a solution?
If we have all names in sorting order (priority given to first name and then last name), then we can use binary search tree to find the given name. then it is less than O(N).
Person is an object which has to be searched and accessed using his name / surname / name+surname.
So an O(logN) solution is possible by creating three sorted arrays one for name, another one for surname and another one for full name. And each will have the pointer to the person object. A binary search will be sufficient for that.
An O(1) solution is possible if we take hashtable or map for all of the three.
Two hashtables. One with key for First Name and other with key for Last Name with both values pointing to same Person object.
For each bucket store items in BST, sorted by the "other" name.
So when searching for complete name, we can do O(1) for First Name and then O(lg n) to find Second Name (or vice versa).
We could create a hash table on names, then each element of the hash table can be another hash table on last names. This would be O(1) ideally. Of course we should have another data structure that hashes on last names and then on first names.
- Igor September 12, 2011