Given a string containing just parentheses, determine if the input string is valid The task
is taken from leetcode


  Given a string containing just the characters '(', ')', '{', '}', '['
  and ']', determine if the input string is valid.
  
  An input string is valid if:
  
  
  Open brackets must be closed by the same type of brackets.
  Open brackets must be closed in the correct order.
  Note that an empty string is also considered valid.
  
  
  Example 1:

Input: "()"

Output: true

  
  Example 2:

Input: "()[]{}"

Output: true

  
  Example 3:

Input: "(]"

Output: false

  
  Example 4:

Input: "([)]"

Output: false

  
  Example 5:

Input: "{[]}"

Output: true



My functional solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = s =&gt; {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  return [...s].every(x =&gt; par[x] 
                      ? rep.push(par[x])
                      : rep.pop() === x) &amp;&amp; !rep.length;
};


My imperative soltion

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid2 = s =&gt; {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  for (let i = 0; i &lt; s.length; i++) {
    if (par[s[i]]) {
      rep.push(par[s[i]]);
    } else {
      if (rep.pop() !== s[i]) {
        return false;
      }
    }
  }
  return rep.length === 0;
};
The code looks quite succinct and sufficient. The only suggestions I would offer are minor tweaks:


for the imperative solution, a for...of loop could be used to eliminate the need to do bookkeeping on the counter variable and use it to index into the string to get each character:

for(const c of s) {
  if (par[c]) {
    rep.push(par[c]);
  } else {
  if (rep.pop() !== c) {
    return false;
  }
}

for the functional solution, the callback function could be declared on a previous line, and then the return line can be reduced to a single line:

const pushOrPopMatch = x =&gt; par[x] ? rep.push(par[x]) : rep.pop() === x
return [...s].every(pushOrPopMatch) &amp;&amp; !rep.length;


That line defining pushOrPopMatch() is 73 characters long, which some might argue is too long for a line, given it would be inside a function and indented at least two spaces, so it may not be ideal