Intersection of three sorted arrays in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in three arrays of integers all sorted in an increasing order. The function should then construct and return an array that contains only those elements that present in all three arrays.

For example −

If the input arrays are −

const arr1 = [4, 7, 8, 11, 13, 15, 17];
const arr2 = [1, 3, 4, 13, 18];
const arr3 = [2, 4, 7, 8, 9, 10, 13];

Then the output should be −

const output = [4, 13];

Example

The code for this will be −

 Live Demo

const arr1 = [4, 7, 8, 11, 13, 15, 17];
const arr2 = [1, 3, 4, 13, 18];
const arr3 = [2, 4, 7, 8, 9, 10, 13];
const intersectThree = (arr1 = [], arr2 = [], arr3 = []) => {
   let curr1 = 0;
   let curr2 = 0;
   let curr3 = 0;
   const res = [];
   while((curr1 < arr1.length) && (curr2 < arr2.length) && (curr3 < arr3.length)){
      if((arr1[curr1] === arr2[curr2]) && (arr2[curr2] === arr3[curr3])){
         res.push(arr1[curr1]);
         curr1++;
         curr2++;
         curr3++;
      }
      const max = Math.max(arr1[curr1], arr2[curr2], arr3[curr3]);
      if(arr1[curr1] < max){
         curr1++;
      };
      if(arr2[curr2] < max){
         curr2++;
      };
      if(arr3[curr3] < max){
         curr3++;
      };
   };
   return res;
};
console.log(intersectThree(arr1, arr2, arr3));

Output

And the output in the console will be −

[4, 13]
raja
Published on 26-Feb-2021 08:18:12
Advertisements