BeginnerStack
Matching brackets with a stack
Push every opening bracket; on a closing one, the top of the stack must be its partner. Last opened, first closed.
The idea
Brackets close in the reverse order they open: the most recently opened must close first. That βlast in, first outβ order is exactly what a stack gives you.
At the end the stack must be empty, or something was opened and never closed.
Worked example
β( [ ] )β and β( ]β
- ( β push β [(] [ β push β [(, [] ] β top is [ β pop ) β top is ( β pop β empty β valid
- ( β push ] β top is ( but needs [ β invalid
In code (Python)
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stackO(n) time, O(n) space.
How to spot it
- Nested structure: brackets, tags, βundo the most recentβ, evaluating expressions.
Common mistakes
- Popping from an empty stack on input like β)β.
- Forgetting the final emptiness check, so β((β passes.
Practise it
Go further
Up next for you Β· Beginner
βHave I seen this?β is a set β