I was asked in an interview this question
LinkedList A has {1,2,3,4,5,6}
LinkedList B has {1,3,5}
I needed to write a method which would return back a Set which does not contain the duplicate elements in list A and B
result { 2,4,6}
I wrote a solution which would iterate over first list and if it does not exist in the second list then add it to a HashSet. But need a solution which performs better than the suggested Algorithm.
No space constraint mentioned for solving this.
Would definitely like a solution using JDK ,but would prefer a solution which is algorithm based
Thanks a ton
The standard solution is to loop through the first list and put everything in a hash table. This is linear time since inserting into a hash table is constant time.
Then loop through the second list and look to see if each element exists in the hash table. If it exists, delete it from the table. Else, add this item to a new list.
Now append everything left in the hash table to the new list.
This second operation is also linear since lookup and deletion are also constant for hash tables. Thus, the overall algorithm is linear.