Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

How to solve parentheses validity checking problems in javascript

✨ Basic : validity check using stack

const stack = [];
for (const ch of str) {
  if (ch === "(") {
    stack.push(ch);
  } else {
    const pop = stack.pop();
    if (pop !== "(") return false;
  }
  return stack.length === 0;
}

πŸ’‘ Tips

For valid parentheses,

  • The number of open parentheses ( (str[0:i])
    • should be equal or greater than the number of close parentheses ).
  • The number of close parentheses ) (str[0:i])
    • can not be greater than the number of open parentheses (.
    • If so, it's invalid parentheses at index i (str[0:i]).

πŸ—’οΈ Typical problems