Stack
Last in, first out: keep what's still open on a stack and close it when its match arrives.
Spot it
Signals in the questionThings open and close in nested order (brackets, tags, function calls).
You need the most recent unresolved item.
"Next greater / smaller element" or undo behaviour.
The idea
O(n) time · O(n) spacePush each opening item. When a closing item arrives it must match the top of the stack, the most recent open one. If the stack is empty at the end, everything was closed in order.
Template · Match the top
1def is_valid(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in pairs:6 if not stack or stack.pop() != pairs[ch]:7 return False8 else:9 stack.append(ch)10 return not stack
The template, filled in for Valid Parentheses. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Popping from an empty stack on a closing bracket that has no partner.
2Forgetting that leftover open items at the end mean invalid.
3Checking only that counts match: "([)]" has equal counts but the wrong order.
Check yourself
Question 1 of 2Why a stack and not a queue for brackets?