Q&A-1Walk through balanced-bracket validation, including where engineers most often get it wrong.
Answer
First 90 seconds
Clarify three things before writing code: which delimiters count ((), [], {} or just one) whether the string is bracket-only or also contains other characters, and whether "" is valid (it is). Then answer: keep the openers on a stack; a closer must match the most recently opened delimiter, so pop and compare; when the input ends, the stack must be empty. One pass, O(n) time, O(d) space for maximum nesting depth d.
If brackets are the whole alphabet, counting is still not enough: ")(" has equal counts and no valid structure, and neither does "([)]".
def valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False # closer with nothing open, or wrong type
else:
return False # contract: input is bracket-only
return not stack # any opener left is unclosedTrace of "({[]})"
| read | stack after |
|---|---|
| ( | ['('] |
| { | ['(', '{'] |
| [ | ['(', '{', '['] |
| ] | ['(', '{'] |
| } | ['('] |
| ) | [] |
Ends empty, so valid. The not stack or ... order is load-bearing: on input ")" the or short-circuits and no pop happens. Written the other way round, stack.pop() != pairs[ch] or not stack raises IndexError on that same input.
Test cases
| input | result | reason |
|---|---|---|
| "" | True | nothing opened, nothing left |
| "({[]})" | True | every closer matches its opener |
| ")(" | False | first character is a closer with an empty stack |
| "([)]" | False | ')' pops '[' and finds a type mismatch |
| "()]" | False | ']' arrives with an empty stack |
| "(((" | False | stack holds three unclosed openers at the end |
Where engineers get it wrong
- Counting instead of matching. ")(" and "([)]" each have equal opener and closer counts, so a counter says valid. Detect it with tests that include balanced-count, invalid-structure strings rather than only the happy path.
- Dropping the final
not stack. "(((" then returns True. One all-openers test catches it. - Popping before checking emptiness, as above. A sentinel opener like "#" instead of the emptiness check avoids the crash but silently accepts the input.
- Validating brackets where brackets are data. A ")" inside a JSON string, a regex literal or a C comment is not structure. Hand-rolled validators pass bracket tests and fail language tests: push the job to json.loads, expat or a real lexer and let it own the state machine. Differential fuzzing against that parser finds the gaps.
- Unbounded depth as an input vector. 10^7 '(' characters grow the list to 10^7 eight-byte pointers, roughly 80 MB, before the function returns False. Production parsers cap nesting depth for exactly this reason; cap yours at a documented maximum and reject past it.
Alternatives, and when the stack is unnecessary
- Single delimiter type: an int counter, O(1) space. Reject the moment it goes negative, require zero at the end.
- Depth bounded by the grammar (say 64): fixed char array plus an index, no allocation, no growth.
- Recursion: same invariant, implicit stack, one frame per nesting level. CPython's default recursion limit is 1000 (sys.getrecursionlimit()), so a recursive validator raises RecursionError on input the loop handles without noticing, and reporting the index of the offending character means threading state through the call chain.
- Regex: only for bounded nesting. A regular expression cannot count arbitrary depth, so (([^()]*)) strips one level at a time; repeated reduction to a fixpoint is not validation.
The explicit stack is never the wrong answer for arbitrary nesting with mixed delimiter types. It is just more machinery than one delimiter type or a grammar-bounded depth needs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.