Given two arrays, how to find the maximum element which is common to both the arrays?
I was thinking of sorting both the arrays(n log n) and then perform the binary sear
You can but using O(N)
space.
Just go through the first array and place all elements in a HashTable
. This is O(N)
Then go through the second array keeping track of the current maximum and checking if the element is in the HashTable
. This is also O(N)
.
So total runtime is O(N)
and O(N)
extra space for the HashTable
Example in Java:
public static int getMaxCommon(int[] a, int[] b){
Set firstArray = new HashSet(Arrays.asList(a));
int currentMax = Integer.MIN_VALUE;
for(Integer n:b){
if(firstArray.contains(n)){
if(currentMax < n){
currentMax = n
}
}
}
return currentMax;
}