Valid Parentheses
Check whether a bracket string is valid.
Pattern fit
This is a stack problem rather than a true monotonic-stack problem, but it trains the exact instinct of using a LIFO structure to resolve the nearest unmatched opener.
Key observation
Every closing bracket must match the most recent unmatched opening bracket, not an arbitrary earlier one.
Target complexity
O(n) / O(n)
How to break down the solution cleanly
This is a stack problem rather than a true monotonic-stack problem, but it trains the exact instinct of using a LIFO structure to resolve the nearest unmatched opener.
Every closing bracket must match the most recent unmatched opening bracket, not an arbitrary earlier one.
Decide what unresolved property the stack maintains.
Push indices while the monotonic invariant holds.
Reference implementation
Python# Generic pattern template
stack = []
for i, value in enumerate(nums):
while stack and nums[stack[-1]] < value:
prev_index = stack.pop()
# value is the next greater for prev_index
stack.append(i)
Common pitfalls
Popping from an empty stack when the string starts with a closing bracket.
Matching bracket types incorrectly when multiple bracket kinds exist.
Common follow-ups
How would you return the first invalid position?
What if wildcard brackets were allowed?
Continue with related problems
Build repeatable depth inside the Monotonic Stack cluster before moving on.