Valid Parentheses: The Stack Problem Every Interview Starts With
In this series: Interview patterns in Python
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.
| i | ch | action | stack after |
|---|---|---|---|
| 0 | ( | opener, push | ( |
| 1 | ) | closer, top is (, match, pop | empty |
| 2 | [ | push | [ |
| 3 | ] | match, pop | empty |
| 4 | { | push | { |
| 5 | } | match, pop | empty |
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.
| i | ch | action | stack 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
| Input | Why it matters | What the code does |
|---|---|---|
"" | Empty string is valid | Length 0, loop does not run, stack is empty, returns True |
"]" | A closer with nothing to match | Odd length, or not stack on the first character, returns False |
"((" | Openers that never close | Loop 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
Subsets: Every Prefix Is a Valid Answer
LeetCode 78 in Python. Emit the power set by recording at every node, recurse with i + 1, and copy the shared buffer before the next pop.
Combination Sum: Reuse the Number, Keep the Index
LeetCode 39 in Python. Enumerate combinations that hit the target, reuse a candidate by staying at the same index, and skip generating permutations.
Generate Parentheses: Backtracking With Two Counts
LeetCode 22 in Python. Build only valid strings with two counters, skip the generate-and-filter trap, and name the Catalan-shaped search tree interviewers expect.
Daily Temperatures With a Monotonic Stack
LeetCode 739 in Python. The stack stores days still waiting for a warmer one, each index is pushed and popped once, and equal temperatures must not count.
Course Schedule: Topological Sort Detects the Cycle
Given prerequisite pairs, decide if a course plan is possible. Kahn's algorithm in Python, the indegree trick, and the cycle case interviewers actually probe.
LRU Cache: OrderedDict Gives You O(1) Get and Put
Design a least-recently-used cache in Python. Why a hash map alone is not enough, how OrderedDict encodes the recency list, and the capacity edge case.
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.