DEV Community

Discussion on: A common coding interview question

Collapse
 
sxync profile image
SaiKumar Immadi • Edited

A simple and straightforward O(m+n) solution.

const FindIntersection = array => {
  const commonNumbers = [];

  const array1 = array[0].split(", ").map(num => Number(num));
  const array2 = array[1].split(", ").map(num => Number(num));

  let index1 = 0;
  let index2 = 0;

  while (index1 < array1.length && index2 < array2.length) {
    if (array1[index1] < array2[index2]) {
      index1 += 1;
    } else if (array2[index2] < array1[index1]) {
      index2 += 1;
    } else {
      commonNumbers.push(array1[index1]);
      index1 += 1;
      index2 += 1;
    }
  }

  return commonNumbers.join(", ");
};

EDIT: I just checked the next article and it has the same solution listed. Sorry I did not check that before posting this here.