Q2: Valid Parentheses

Given a string containing (), {}, and [], determine if the input string is valid using a Stack data structure.

Stack Parentheses Validator
function isValid(s) {
  const stack = [];
  const pairs = { ')': '(', '}': '{', ']': '[' };
  
  for (let char of s) {
    if (char === '(' || char === '{' || char === '[') {
      stack.push(char);
    } else {
      if (stack.pop() !== pairs[char]) return false;
    }
  }
  return stack.length === 0;
}

console.log(isValid('({[]})')); // true
💡 Opening brackets are pushed onto the stack. When a closing bracket is encountered, we pop the stack and verify that it matches the corresponding opening bracket type.
Key Takeaways
  • Stacks enforce Last-In, First-Out (LIFO) tracking for nested structure validations.
  • The string is invalid if an unexpected closing bracket appears or if brackets remain on the stack at the end.
Knowledge Check

What condition indicates an unclosed opening bracket after processing the entire string?