Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the maximum element which is common in two arrays?

Tags:

algorithm

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 search of every element from one sorted array(starting from larger one) in another array until match is found.

eg:

a = [1,2,5,4,3]
b = [9,8,3]

Maximum common element in these array is 3

Can we do better than n log n?

like image 264
sushil Avatar asked Jun 21 '12 15:06

sushil


People also ask

How do you find the longest common subsequence in two arrays?

Let dp[i][j] be the longest common subarray of A[i…] and B[j…]. Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1. The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays.

How do you find the maximum number of elements in an array?

To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.


2 Answers

With some extra space you could hash in 1 array, then do a contains on each element of the other array keeping track of the biggest value that returns true. Would be O(n).

like image 116
Kevin DiTraglia Avatar answered Oct 20 '22 01:10

Kevin DiTraglia


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<Integer> firstArray = new HashSet<Integer>(Arrays.asList(a));  
  int currentMax = Integer.MIN_VALUE;  
  for(Integer n:b){  
     if(firstArray.contains(n)){  
         if(currentMax < n){  
              currentMax = n  
         }
     }   
  }   
  return currentMax;  
}  
like image 7
Cratylus Avatar answered Oct 20 '22 02:10

Cratylus