Saturday, February 18, 2012

Merge 2 Sorted Arrays, such that integer in both array is copied once.

Write code to merge two arrays in sorted order such that if an integer is in both arrays, it only gets put into the new array once. 
What if you knew that one array was much longer than the other? Could you optimize it?


Input Arrays with repeated elements:
int [] A = {1, 1, 2, 2, 3};
int [] B = {2, 3, 3, 4};
Output:
Merged Array: 
1 1 2 2 3 3 4 


Input Arrays with unique elements:
int [] C = {2, 5, 7, 9, 10, 11};
int [] D = {1, 3, 5, 7, 8, 9, 11, 13};
Merged Array: 
1 2 3 5 7 8 9 10 11 13 


time complexity: O(lenA+lenB) = O(m+n).
space complexity: O(m+n);


Suppose array A is much larger than array B.
Now, take B[0] and do binary search in A for B[0].
If we find it at index i, then copy the data A[0]..A[i] to C;
Otherwise find index i in A, such that A[i] is less than B[0] and A[i+1] is greater than B[0].
Copy A[0]..A[i] to C and then copy B[0] to C at k=i+1;


Now, lets take B[1] and again do binary search for B[1] in A.
if we find it at index j, then copy A[i+1]..A[j] to C.
Otherwise find index j in A, such that A[j] < B[1] and A[i+1] > B[0].
Copy A[i+1]...A[j] to C and then copy B[1] to C at k=j+1;


So on...
suppose n = A.length; and m = B.length;
time complexity: O(m log n)
space complexity: O(m+n)

No comments:

Post a Comment