Stacks and Queues
Balanced Parentheses
Walk a string of bracket characters. Push every opening bracket. On a closing bracket, pop and verify the popped opener matches. Mismatch or empty-stack pop means unbalanced; an empty stack at the end means balanced.
Algorithm
Canonical balanced input is "({[]})"; the stack grows to three elements
then empties as the closers arrive in matching order.
Basic Implementation
basic.py
text = "({[]})"
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
balanced = True
for ch in text:
if ch in "({[":
stack.append(ch)
else:
if not stack or stack[-1] != pairs[ch]:
balanced = False
break
stack.pop()
if stack:
balanced = False
print(balanced)
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- Python: a
listis a fine stack —append/popwork in O(1). - The replay shows the current character, the operation (
pushvs.pop), and the post-step stack contents using a literal[(, {, []notation rather than any object identity.
push opener pop matching closer
Each closing bracket must match the most recent unmatched opener.