Editorial for Balanced Parentheses


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Approach

Use a stack of opening brackets.

Scan the string from left to right:

  • If the character is an opening bracket, push it onto the stack.
  • If it is a closing bracket, the top of the stack must be the matching opening bracket.
    • If the stack is empty or the top does not match, the string is not balanced.
    • Otherwise, pop the top.

After processing all characters, the string is balanced exactly when the stack is empty.

Time complexity is O(|s|).

Solution (Python)

s = input().strip()

pairs = {")": "(", "]": "[", "}": "{"}
opens = set(pairs.values())
stack: list[str] = []

for ch in s:
    if ch in opens:
        stack.append(ch)
    else:
        if not stack or stack[-1] != pairs[ch]:
            print("NO")
            raise SystemExit
        stack.pop()

print("YES" if not stack else "NO")

Comments

There are no comments at the moment.