◀ THE GRIND — STACK

Valid Parentheses

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

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 HINTS — TAKE 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 BOARD — THE 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 SPLITS — TWO PACES, TWO LANGUAGES
grind/valid-parentheses.pyRACE 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-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED