DEV Community

loading...

Discussion on: A coding interview question asked at Google

Collapse
sxync profile image
SaiKumar Immadi

Stack solution using JavaScript array methods push and pop. O(n).

const checkEquivalentKeypresses = array => {
  const array1 = array[0].split(",");
  const array2 = array[1].split(",");

  const firstString = [];
  const secondString = [];

  array1.forEach(char => {
    if (char === "-B") {
      firstString.pop();
    } else {
      firstString.push(char);
    }
  });

  array2.forEach(char => {
    if (char === "-B") {
      secondString.pop();
    } else {
      secondString.push(char);
    }
  });

  return firstString.join() === secondString.join();
};
Collapse
bpedroza profile image
Bryan

I did something really similar except used map instead of duplicating the block for array1 and array2. I think these read better than some of the more compact solutions.