educative.io

Simple queues, no lookback, 9.5 minutes

I don’t see the need for DP. The solution is provided; just make two queues out of m and n.

const findSI = function(m, n, p) {
  if(m.length + n.length !== p.length) return false; // degraded case needs no char comparison
  m = m.split('');
  n = n.split('');
  p = p.split('');
  for (let char of p) {
    if(m[0] === char) {
      m.shift();
      continue;
    }
    if(n[0] === char) {
      n.shift();
      continue;
    }
    return false;  // out of order
  }
  return !m.length && !n.length; // true if all chars used.
};

nvm. The simple queues code does not work for all test cases. When char 0 of the 2 queues is equal, the first is taken (n’s or m’s, depending on the order of if statements).
“aabc”
“abad”
“aabcabad”