valid-parentheses.sh — zsh
stringsstack

Return whether a string containing only parentheses, square brackets, and braces is balanced. Every closing bracket must match the most recent unmatched opening bracket.

Input / output

  • Input: s: string
  • Output: boolean

Examples

  1. "()[]{}" returns true.
  2. "([)]" returns false because the nesting order is invalid.

Constraints

  • 0 <= s.length <= 100,000
  • s contains only parentheses, square brackets, and braces.

Follow-up Can you reject impossible inputs early, and what information must the stack retain?

Examples
Example 1
Input: s = "()"
Output: true
Example 2
Input: s = "()[]{}"
Output: true
Example 3
Input: s = "(]"
Output: false
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.