DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 71

The task is to find the elements that exist in both arrays, given two sorted arrays.

The boilerplate code

function intersect(arr1, arr2) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Because the 2 arrays are sorted, both of them can be walked through at the same time. Start at the beginning of both arrays using two pointers

let i = 0, j = 0;
const result = [];
Enter fullscreen mode Exit fullscreen mode

Compare the current elements, if they are equal, it means an element present in both arrays has been found.

  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] === arr2[j]) {
      result.push(arr1[i]);
      i++;
      j++;
    } 
}
Enter fullscreen mode Exit fullscreen mode

If the element in the first array is smaller, push that pointer forward.

 else if (arr1[i] < arr2[j]) {
      i++;
    }
Enter fullscreen mode Exit fullscreen mode

If the element in the second array is smaller, push that pointer forward

else {
 j++;
}
Enter fullscreen mode Exit fullscreen mode

Continue until the end of the array is reached.

The final code

function intersect(arr1, arr2) {
  // your code here
  let i = 0; j = 0;
  const result = [];

  while(i < arr1.length && j < arr2.length) {
    if(arr1[i] === arr2[j]) {
      result.push(arr1[i]);
      i++;
      j++;
    } else if(arr1[i] < arr2[j]) {
      i++;
    }
    else {
      j++;
    }
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)