DEV Community

Discussion on: Valid parentheses, solving a Facebook interview question.

Collapse
 
vladflorescu94 profile image
vladflorescu94 • Edited

I conduct interviews (not at Facebook), I don't ask questions about algorithms, but I wouldn't probably hire someone who writes code like that, especially if it's a mid-senior position, because there are too many bad practices:

  • var shouldn't be used anymore;
  • variables should have more descriptive names and start with a lowercase character;
  • always ===, never ==;
  • static constants should be defined outside functions;
  • renturn stack.length === 0 is cleaner.

I wrote the implementation below and I find it much cleaner.

const CLOSING_BRACKET_BY_MATCH = {
  '(': ')',
  '[': ']',
  '{': '}',
};

const testBrackets = (input) => {
  const stack = [];
  let len = 0;

  if (input.length % 2 !== 0) {
    return false;
  }

  for (const character of input) {
    if ('([{'.indexOf(character) !== -1) {
      stack.push(character);
      len += 1;
    } else {
      const lastCharacterPushed = stack[len - 1];

      if (len === 0 || (CLOSING_BRACKET_BY_MATCH[lastCharacterPushed] !== character)) {
        return false;
      }

      stack.pop();
      len -= 1;
    }
  }

  return len === 0;
};
Enter fullscreen mode Exit fullscreen mode