Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Stack

Valid Parentheses

EASY✓ CHIP-TIMEDLC #20 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Decide whether a string of round, square, and curly brackets closes correctly — every bracket must be closed by the same type, in the right order, with nothing left dangling.

A string made only of the six bracket characters — (), [], {} — arrives, and the job is to decide whether it's properly balanced.

Balanced means every opening bracket is eventually closed by a bracket of the exact same type, and the closing happens in the right nested order — the most recently opened bracket must be the next one closed.

A string counts as valid only when the entire input closes cleanly with nothing left open and nothing closed out of turn; anything else counts as invalid.

  • string length ranges from empty to several thousand characters
  • only the six characters ( ) [ ] { } ever appear
  • closing order must match the most recently opened bracket
  • answer is a single true or false verdict
EX 01
s = "()"
→ true
simplest valid pair
EX 02
s = "()[]{}"
→ true
back-to-back, all three types
EX 03
s = "(]"
→ false
wrong closing type

The hintstake only what you need

HINT 1 THE NUDGE

Only the most recently opened bracket can legally be the next one closed. Anything that respects that ordering is valid; anything that violates it isn't.

HINT 2 THE STRUCTURE

A stack is built for exactly this: last opened, first closed. Push every opening bracket you see.

HINT 3 ONE STEP FROM THE ANSWER

On a closing bracket, pop the stack and check it matches; a mismatch or an empty stack means invalid, and the string is valid only if the stack is empty once you've read it all.

Coach's boardthe pattern, step by step

STACK OF OPENSPATTERN · STACK MATCHINGs = "([{}])"
(
[
{
}
]
)
STACK OF OPENS
— empty —
STEP 1

Only three bracket shapes matter: push an open, and a close must match the top of the stack.

STEP 1 / 8 · ← → WORK TOO

The splitstwo paces, two languages

grind/valid-parentheses.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def isValid(self, s: str) -> bool:
        closer_to_opener = {")": "(", "]": "[", "}": "{"}
        stack = []
        for ch in s:
            if ch in closer_to_opener:
                if not stack or stack.pop() != closer_to_opener[ch]:
                    return False
            else:
                stack.append(ch)
        return not stack
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 11 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED