A = [9, 1, 4, 2, 5] k unique integers
B = [3, 1, 8, 7, 6, 5] n unique integers
Intersection => [1, 5]
Find an algorithm that uses \$O(1)\$ space (the space used by the return variable is not considered) and runs as fast as possible to find the intersection of the arrays.
private static List<Integer> getIntersectionO1Space(List<Integer> a, List<Integer> b)
{
List<Integer> intersection = new ArrayList<Integer>();
mergeSort(a); //Time O(k log k), space O(1)
for (Integer n : b) //O(n log k)
{
int r = Collections.binarySearch(a, n); //O(log k)
if (r > -1)
intersection.add(n);
}
return intersection;
}
So the total time complexity is \$O(\max(k,n) \log k)\$.
But my solution doesn't utilize the property that "no duplicate elements in the array". I wonder whether there is an algorithm that uses the property and runs faster.