Saturday, December 14, 2013

Given two arrays of integers, unsorted. Write a program to find the common elements within the two.


A[] = {};
B[] = {};

based on hashset => 0(n)

if array is sorted:
for each element of an array A, perform a binary search for that element on the other array B. this takes O(lg n) for each element of A, so it takes a total of n*O(lg n) time

If one array is size n, and the other m, then we can do it in either O(n log m) or O(m log n), depending on which array you choose to do the binary search in.

if m is much larger than n, then O(n log m) would be preferable, So you pick the array with lesser elements and go through each of that and do a binary search on the larger array.

No comments:

Post a Comment