Every opening needs the right ending.
Use nesting order rather than counting opening and closing symbols.
01 Model the idea
Balanced bracket matching is about order and type, not merely equal counts. The most recently opened bracket must be the next one closed, which is exactly a stack’s rule. Ignore ordinary characters, push opening brackets, and match closing brackets against the stack top. A completed scan is valid only if no opening remains.
The stack contains exactly the unmatched openings in nesting order.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
PUSH every opening
FOR each closing: match and pop the latest opening
REQUIRE an empty stack at the end03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def balanced(text):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for character in text:
if character in pairs.values(): stack.append(character)
elif character in pairs:
if not stack or stack.pop() != pairs[character]: return False
return not stack
print(balanced("{a:[(b)]}"))
print(balanced("([)]"))True False
- 1
The stack stores unresolved openings in nesting order. A closing character must correspond to its most recent entry.
- 2
A closing bracket with an empty stack is an immediate failure. Leftover openings at the end are also a failure.
- 3
This is a bracket exercise, not a complete programming-language parser. Quoted strings, comments, and escape sequences would require lexical analysis before deciding which characters count as syntax.
04 Count the cost
O(n)
O(n) worst-case stack
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Test empty text, an unmatched closing bracket, and unfinished opening brackets.
Reveal one possible solution +
def balanced(text):
pairs, stack = {')':'(', ']':'[', '}':'{'}, []
for ch in text:
if ch in '([{': stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]: return False
return not stack
assert balanced("")
assert not balanced(")")
assert not balanced("((")
print("Nesting checks passed")06 Check your reasoning
Why use a stack?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.