JavaScript Program for find common elements in two sorted arrays


We are required to write a JavaScript function that takes in two sorted arrays (both sorted in the same order). The function should prepare and return a third array that contains all those elements that are common to both.

We can easily solve this problem by using two loop in O(m * n) time (m and n being the respective length of the arrays) or even in O(m + n).

But since the arrays are sorted, we can save ourselves time by iterating over the array smaller in size and searching elments in the bigger array using binary search algorithm.

This way, the time complexity of the function will be reduced to O(n * logm) (m > n) which is far better than O(m + n), especially in cases where m >> n

Example

The code for this will be −

const arr1 = [2, 5, 7, 8, 9, 11, 14];
const arr2 = [1, 3, 4, 5, 6, 8, 11, 16];
const binarySearch = (target, arr = []) => {
   let first = 0;
   let last = arr.length − 1;
   let position = −1;
   let found = false;
   let middle;
   while (found === false && first <= last) {
      middle = Math.floor((first + last)/2);
      if (arr[middle] == target) {
         found = true;
         position = middle;
      } else if (arr[middle] > target) {
         last = middle − 1;
      } else {
         first = middle + 1;
      }
   }
   return position;
}
const findCommon = (arr1 = [], arr2 = []) => {
   const res = [];
   for (let i = 0; i < arr1.length; ++i){
      if (binarySearch(arr1[i], arr2) !== −1){
         res.push(arr1[i]);
      };
   };
   return res;
};
console.log(findCommon(arr1, arr2));

Output

And the output in the console will be −

[5, 8, 11]

Updated on: 24-Nov-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements