Amazon Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
I am not totally sure but this should work.
Store the First array in a hashmap using the integer as key and a flag value of 1.
Now read the second array, and try and find a hit for that value in the first hashmap.
If you get a hit or a flag value of one corresponding to that value from the second array, direct it to the output.
In case the array is very large to fit in memory in one go, read n values at a time.
Complexity If m is the total number of integers in the large array
( m/n )*n. or mn or O(N)
I guess this should do
void union(int[] a, int[]b){
int smallArray[] = null;
int largeArray[] = null;
if(a.length<b.length){
smallArray = a;
largeArray = b;
}else{
smallArray = a;
largeArray = b;
}
HashSet<Integer> set = new HashSet<Integer>();
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.ensureCapacity(largeArray.length+smallArray.length);
for(int i:smallArray)
set.add(i);
for(int i :largeArray)
if(!set.contains(i))
arr.add(i);
for(int i: set)
System.out.print(i + " ");
for(int i:arr)
System.out.print(i+ " ");
}
Assuming the 2 arrays are very large to it into the memory, use merge sort, and during merging phase discard if duplicates are found.
- Praveen Kumar July 27, 2012This will work in O(NlogN) where N = sizeof(array1) + sizeof(array2);