6 min readRishi

Valid Parentheses: The Stack Problem Every Interview Starts With

In this series: Interview patterns in Python

Valid Parentheses: The Stack Problem Every Interview Starts With

Valid Parentheses is LeetCode 20, rated Easy, and it is asked constantly because it tests one idea cleanly: the most recently opened bracket must be the first one closed. That is last-in, first-out. That is a stack. If you reach for a counter, you will pass () and fail ([)], and the interviewer will ask you why.

This is one of a small set of interview-pattern notes. The stack you build here is the same structure Daily Temperatures uses with indexes instead of characters.

What "valid" actually requires

Given a string containing only (, ), {, }, [, and ], return whether it is valid. Valid means every opening bracket is closed by the same type, in the correct order, and every closing bracket has a matching open one before it.

()[]{} is valid. ([)] is not. (] is not. ] is not. "" is valid. (()) is valid. Interleaving two types without nesting them in order is the usual fail.

Two code paths, one stack

Push openers. On a closer, the top of the stack must be its matching opener. At the end, the stack must be empty.

Odd length can never be valid: every pair consumes two characters. Check that first. Empty string has length 0, which is even, so it still falls through to not stack.

def isValid(s: str) -> bool:
    if len(s) % 2 == 1:
        return False
    pairs = {")": "(", "]": "[", "}": "{"}
    stack: list[str] = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return not stack

Time is O(n): one pass, constant work per character. Space is O(n) in the worst case, a string of all openers. The length check fails odd inputs in O(1); it does not buy O(1) space on even inputs.

Two details separate a clean answer from a fumbled one. The dictionary is keyed by the closer, so you never write six if branches. And the return is not stack, not True. Returning True after the loop passes ((). Say the empty-stack check out loud when you write if not stack. That is the crash they are waiting for.

Dry-run: ()[]{} then ([)]

Walk ()[]{} on a board. Stack starts empty.

ichactionstack after
0(opener, push(
1)closer, top is (, match, popempty
2[push[
3]match, popempty
4{push{
5}match, popempty

Loop ends. not stack is true. Valid. Adjacent pairs never nest, and that is allowed. The stack goes empty three times. That is not a bug; it means each pair resolved before the next opened.

Now ([)]. This is the string a counter gets wrong.

ichactionstack after
0(push(
1[push( [
2)closer, need (, top is [reject

You never reach ]. The string has the right counts — one of each opener and closer — and still fails. The top of the stack is [, so the closer that is legal here is ]. A ) is a type mismatch, not "some closer." Return False at index 2.

Swap the last two characters to ([]) and the same first two pushes happen, then ] matches [, then ) matches. Valid. Crossing vs nesting is the entire difference.

"]" is odd, so the length check returns immediately. Without it, not stack is true on the first character. Same answer. "([)]" is even; it still needs the table above.

The three edge cases they will try

InputWhy it mattersWhat the code does
""Empty string is validLength 0, loop does not run, stack is empty, returns True
"]"A closer with nothing to matchOdd length, or not stack on the first character, returns False
"(("Openers that never closeLoop finishes, stack has two items, not stack is False

The second case crashes a solution that pop()s before checking emptiness. IndexError is not return False. "(}" is a type mismatch: top is (, closer wants {'s partner. "{[]}" is nested three types, all legal — add one nested example if you only tested adjacent pairs.

Why a counter fails

A single depth counter — increment on open, decrement on close, fail if it goes negative — is correct for one bracket type. With three types it loses which bracket is open. ([)] stays non-negative and ends at zero. The stack rejects it when ) meets [ on top. Three counters still fail ([)] if you only check each count returns to zero. You need order. The stack is the order. O(1) space is possible for one type, not for mixed types. Say the restriction.

Follow-ups that turn it into a design question

Minimum removals to make it valid. Track indexes of unmatched openers and unmatched closers. Remove both sets. LeetCode 1249 for parentheses only. Same stack, indexes instead of characters.

Longest valid substring. Push indices, seed the stack with -1, and on each closer compute i - stack[-1] after popping. LeetCode 32. A leftover opener becomes the new boundary.

Generate all valid strings of n pairs. Same invariant: never place a closer that would make closed > opened. That is Generate Parentheses.

Wildcard *. Usually "exists a valid assignment," not enumerate. Clarify whether * can be (, ), or empty. Greedy two-pass or a stack of stars plus openers. Do not start three-way recursion until they ask.

Streaming / tags. The loop already consumes one token at a time. Stack size is nesting depth, not file length. HTML is the same loop after you tokenize; mismatched div vs span is ) vs [.

When this is the wrong tool

One bracket type plus O(1) space: use a counter. Quotes around brackets: a tokenizer, not this dictionary. Unicode brackets: ask. The length check is not the insight. LIFO plus not stack is.

The interviewer is watching whether you check emptiness before you pop, whether you return not stack, whether you can dry-run ([)] against ()[]{}, and whether you can say in one sentence why a counter is not enough.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.