#155
Medium
Monotonic Stack

Min Stack

Design a stack that supports retrieving the minimum in O(1).

StackDesign

Pattern fit

The simplest solution keeps a second stack of running minimums, which is a good reminder that stack questions are often about storing extra structural history.

Key observation

Each push must also record what the minimum becomes at that depth.

Target complexity

O(1) / O(n)

How to break down the solution cleanly

1

The simplest solution keeps a second stack of running minimums, which is a good reminder that stack questions are often about storing extra structural history.

2

Each push must also record what the minimum becomes at that depth.

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

Only storing a new min when the value is smaller and failing duplicate minimums.

warning

Trying to recompute the minimum after pop.

Common follow-ups

How would you compress duplicates in the min stack?

What changes if you also need max in O(1)?

Continue with related problems

Build repeatable depth inside the Monotonic Stack cluster before moving on.

view_weekBack to the pattern page
LeetCode 155. Min Stack Guide | Interview AiBox