Sunday, 17 June 2012

Find similarity between two arrays

There are two arrays.
int arr1[5] = { 3, 5, 2, 5, 2}
int arr2[5] = { 2, 3, 5, 5, 2}
The arrays will be called similar if they contain same number of elements equally.
Write the pseudo code to check this ?
I was not allowed to use sorting and hashtable.
Solution:
I.
Pick a random number from the array and partition it using the quick sort partition function.
Then partition the second array using the same number. O(n) time.

Now recursively, do this until the counts on either side mis-matches.

II.
Make two min heaps in O(n) time.
Extract the mins from both and compare till either both heaps are empty or there is a mismatch.

Reference: http://www.careercup.com/question?id=11685824

2 comments: