Google Interview Question: Given two linked lists, retur... | Glassdoor

Interview Question

Software Engineer Interview

Given two linked lists, return the intersection of the two

  lists: i.e. return a list containing only the elements that occur in both of the input lists.

Interview Answer

3 Answers


Traverse the first list. Insert all the elements in the list into a hash table. Complexity: O(n)
Traverse the second list. For each element in the list, look it up in the hash table. If it is in the hash table, then insert it into the destination list. Complexity: n * O(1) = O(n)
Total complexity: O(n)

Radu Litiu on Oct 13, 2009

Hi Radu Litiu,

Your solution is correct though the complexity analysis is incorrect.

Insertion and lookup from the hashtable can take a worst case performance of O(n) or O(logn) if you use a priority queue as the backend storage. This means that while traversing the lists for n times, each time you can encounter a O(n) complexity thus resulting in a worst case performance of O(n^2), or at least O(nlogn).

neakor on Nov 7, 2009

Here is where I am confused: A hashtable is supposed to have a O(1) lookup, is it not?

The actual implementation of a hash table is platform specific. For e.g. C++ hashtables are Balanced binary search trees?

vic on Nov 27, 2009

Add Answers or Comments

To comment on this, Sign In or Sign Up.