The thing is depending on which position you're interviewed. They probably were interested in your logic. One of possible solution is to start with a simple method:
public Set<Integer> killDuplicates(LinkedList<Integer> a0, LinkedList<Integer> a1) {
Set<Integer> common = new HashSet<Integer>();
common.addAll(a0); //one could pass thru constructor, no matter
common.retainAll(a1);
Set<Integer> result = new HashSet<Integer>();
result.addAll(a0);
result.addAll(a1);
result.removeAll(common);
return result;
}
But still this could be dramatically slow in some cases, and there are very many ways to improve speed of this code.
One of possible solutions is to use special structures for fast set intersection.
Sorting is good, but since we have data in LL it would use merge sort (additional memory written in pseudo code but feel free to ask questions):
public Set<Integer> killDuplicatesSorted(...) {
//sort a0
//sort a1
Iterator i0 = a0.getIterator();
Iterator i1 = a1.getIterator();
while (i0 != end && i1 != end) {
if (i0.current == i1.current) {
//skip presented in both
i0.moveNext();
i1.moveNext();
} else if (i0.current < i1.current) {
result.add(i0.current);
i0.moveNext();
} else {
result.add(i1.current);
i1.moveNext();
}
}
while (i0 != end) {result.add(i0.current); i0.moveNext();}
while (i1 != end) {result.add(i1.current); i1.moveNext();}
return result;
}
removeAll()implementations