What is the best algorithm to find all duplicates in two arrays?
What I can think of is brute force algorithm.
Comparing two arrays directly, and once found the same number, store it in the auxiliary array. But the time complexity is O(n2).
What is the best algorithm to find all duplicates in two arrays?
What I can think of is brute force algorithm.
Comparing two arrays directly, and once found the same number, store it in the auxiliary array. But the time complexity is O(n2).
That will be O(n+m) (sizes of the arrays).
There is an O(n log n) algorithm.
Sort arr1 and arr2 using quick sort or merge sort
i = 0
j = 0
found = 0
while i < arr1.length and j < arr2.length:
if (arr1[i] == arr2[j])
found = found + 1
i = i + 1
j = j + 1
else if (arr1[i] < arr2[j])
i = i + 1
else
j = j + 1
Sort the array, then go through both arrays at the same time, always advance an array when the current element is smaller than the other. Complexity: O(nlogn)
You can identify duplicates in arrays in O(n) time. This approach uses hashmap, heres pseudocode:
// a and b are input arrays
HashMap h
for e in a:
if h[e] == 0:
h[e]++
for e in b:
if h[e] != 0:
h[e]++
for e in h:
if e > 1:
print "Duplicate" + e
Hashmap[Element]
is syntactic sugar and means:
Get element with key e, if no present, then create it with initializer 0