Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Algorithm) Find if two unsorted arrays have any common elements in O(n) time without sorting?

We have two unsorted arrays and each array has a length of n. These arrays contain random integers in the range of 0-n100. How to find if these two arrays have any common elements in O(n)/linear time? Sorting is not allowed.

like image 971
Omerta Avatar asked Dec 28 '10 16:12

Omerta


1 Answers

Hashtable will save you. Really, it's like a swiss knife for algorithms.
Just put in it all values from the first array and then check if any value from the second array is present.

like image 128
Nikita Rybak Avatar answered Sep 30 '22 19:09

Nikita Rybak