DEV Community

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

Collapse
 
js_bits_bill profile image
JS Bits Bill • Edited

I gave this a shot! Similar to yours, my approach was to split the string and track the expected closing parens in a separate array. I used the every method instead of a for...of loop which works nicely with the empty string case.

const isValid = function(str) {

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

  const closingParens = [];
  return [...str].every(validate);

  function validate(char, i, arr) {
    const isLastChar = i === arr.length - 1;

    // If char found in pairs, push closing paren to arr
    if (pairs[char] && !isLastChar) {
      closingParens.push(pairs[char]);
      return true;

    } else {
      // If char has no closing paren, return false
      if (!closingParens.length) return false;

      // Check if current char is last in arr
      const lastCharInArray = closingParens.pop();

      // If last char and unmatched parens, return false
      if (isLastChar && closingParens.length) return false;

      // If pair found, continue
      if (char === lastCharInArray) return true;
    }
  }
};

What do you think?

Collapse
 
akhilpokle profile image
Akhil

For :"{[]}" it returns false.

Try solving it here : leetcode.com/problems/valid-parent...

Collapse
 
js_bits_bill profile image
JS Bits Bill

@akhil I updated it to meet that condition!