#20
Easy
Monotonic Stack

Valid Parentheses

Check whether a bracket string is valid.

StringStack

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

1

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.

2

Every closing bracket must match the most recent unmatched opening bracket, not an arbitrary earlier one.

3

Decide what unresolved property the stack maintains.

4

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

warning

Popping from an empty stack when the string starts with a closing bracket.

warning

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.

view_weekBack to the pattern page
LeetCode 20. Valid Parentheses Guide | Interview AiBox