Maintain a stack that can report both its newest value and its smallest current value.
Problem
Input. Calls to push(value), pop(), top(), and get_min() on an initially empty MinStack of integers.
Output. top returns the newest remaining value, and get_min returns the smallest remaining value.
The pop operation removes the newest value without returning it.
Rules. Equal minima are separate entries and must survive removal of another equal entry.
Minimum queries must not scan the stack. Calls to pop, top, or get_min require a nonempty stack.
Empty calls raise IndexError in the reference.
Example. After push(5), push(2), and push(4), top() returns 4 and get_min() returns 2.
After one pop(), both queries return 2.
Picture: Each Level Saves Its Own Answer
Problem trace
Each stack entry remembers the minimum that existed beneath it
- top
- (0, 0)
- columns
- value | minimum so far
- layout
- bottom to top
- action
- initialize→minimum = 5
- v / row 0
- empty→5
- a / row 0
- empty→5
- top
- (0, 0)→(1, 0)
- action
- minimum = 5→min(2, 5) = 2
- v / row 1
- not shown→2
- top
- (1, 0)→(2, 0)
- action
- min(2, 5) = 2→min(4, 2) = 2
- v / row 2
- not shown→4
- action
- min(4, 2) = 2→top pair minimum = 2
- returned
- not shown→2
- top
- (2, 0)→(1, 0)
- action
- top pair minimum = 2→remove (4, 2)
- returned
- 2→not shown
- action
- remove (4, 2)→top pair minimum = 2
- returned
- not shown→2
- action
- top pair minimum = 2→top pair value = 2
- result
- not shown→top() = 2; get_min() = 2
- returned
- 2→not shown
- Recognize it
- Use this pattern when ordinary stack operations must also answer an aggregate such as the current minimum in constant time, including immediately after pops.
- Keep true
- For every stored pair (value, minimum), minimum equals the smallest value from the bottom through that pair; therefore the top pair summarizes the complete current stack.
- Reuse it
- Attach any reversible prefix summary needed later to each stack item; the same technique supports max stacks, depth summaries, and constant-time aggregate reads after rollback.
Reference drawing
Problem trace
Each stack entry remembers the minimum that existed beneath it
Execution trace
- top
- (0, 0)
- columns
- value | minimum so far
- layout
- bottom to top
- action
- initialize→minimum = 5
- v / row 0
- empty→5
- a / row 0
- empty→5
- top
- (0, 0)→(1, 0)
- action
- minimum = 5→min(2, 5) = 2
- v / row 1
- not shown→2
- top
- (1, 0)→(2, 0)
- action
- min(2, 5) = 2→min(4, 2) = 2
- v / row 2
- not shown→4
- action
- min(4, 2) = 2→top pair minimum = 2
- returned
- not shown→2
- top
- (2, 0)→(1, 0)
- action
- top pair minimum = 2→remove (4, 2)
- returned
- 2→not shown
- action
- remove (4, 2)→top pair minimum = 2
- returned
- not shown→2
- action
- top pair minimum = 2→top pair value = 2
- result
- not shown→top() = 2; get_min() = 2
- returned
- 2→not shown
- Recognize it
- Use this pattern when ordinary stack operations must also answer an aggregate such as the current minimum in constant time, including immediately after pops.
- Keep true
- For every stored pair (value, minimum), minimum equals the smallest value from the bottom through that pair; therefore the top pair summarizes the complete current stack.
- Reuse it
- Attach any reversible prefix summary needed later to each stack item; the same technique supports max stacks, depth summaries, and constant-time aggregate reads after rollback.
| Operation | Stored pairs, bottom to top | Result |
|---|---|---|
push(5) | (5, 5) | None |
push(2) | (5, 5), (2, 2) | None |
push(4) | (5, 5), (2, 2), (4, 2) | None |
get_min() | Unchanged | 2 |
pop() | (5, 5), (2, 2) | None |
get_min(); top() | Unchanged | 2; 2 |
Each pair’s second field is the minimum from the bottom through that level.
A push combines its value with the preceding saved minimum. A pop removes one pair, leaving every earlier summary unchanged.
Duplicate minima retain separate levels: push(2), push(2), pop() must still report 2.
Code
class MinStack:
def __init__(self) -> None:
self.stack: list[tuple[int, int]] = []
def push(self, value: int) -> None:
minimum = min(value, self.stack[-1][1]) if self.stack else value
self.stack.append((value, minimum))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def get_min(self) -> int:
return self.stack[-1][1]
Indexed reads are constant-time; Python list pushes and pops are amortized , not strict worst-case guarantees. Storage is pairs for entries, under ordinary integer-comparison costs.
Change 1: Save Minimum and Maximum
New task. Query both bounds after rollback.
Picture and change. Store (value, minimum, maximum) per level.
Code.
class MinMaxStack:
def __init__(self):
self.stack = []
def push(self, value):
minimum = min(value, self.stack[-1][1]) if self.stack else value
maximum = max(value, self.stack[-1][2]) if self.stack else value
self.stack.append((value, minimum, maximum))
def pop(self):
self.stack.pop()
def limits(self):
return list(self.stack[-1][1:])
def minmax_rollback(values):
stack = MinMaxStack()
for value in values:
stack.push(value)
before = stack.limits()
stack.pop()
return [before, stack.limits()]
Check. [5, 2, 1] gives [[1, 5], [2, 5]]. The wrapper requires at least two values.
Use when. Several constant-size prefix summaries are needed.
Change 2: Observe Every Restored Minimum
New task. Report minima during all pushes and pops.
Picture and change. Use the retained MinStack; never query after its final pop.
Code. Place after MinStack:
def minima_during_rollback(values):
stack = MinStack()
answer = []
for value in values:
stack.push(value)
answer.append(stack.get_min())
for remaining in range(len(values) - 1, -1, -1):
stack.pop()
if remaining:
answer.append(stack.get_min())
return answer
Check. [5, 2, 4] gives [5, 2, 2, 2, 5]; [2, 2] gives [2, 2, 2]; empty input gives [].
Use when. The caller needs an auditable sequence; its output needs additional storage.
Failure: Keeping Only One Minimum
When the minimum is popped, one scalar cannot recover the previous minimum without retained history or a rescan.
Transfer Check
Must the aggregate have an inverse?
Reasoned Answer
No. Earlier prefix answers remain stored at their own levels. Pop restores state instead of undoing min algebraically.
Restoration Is Not an Inverse
Both min(5, 1) and min(9, 1) produce 1. The result and last value alone cannot identify the earlier answer.
The stack avoids that information loss by keeping each earlier summary alongside its corresponding prefix.
The min/max extension preserves amortized constant operation costs and linear stored state.
Its limits operation returns [minimum, maximum] and requires a nonempty stack, as does pop.
The trace wrapper needs two initial entries because it queries before and after one removal.
This structure supports last-in-first-out rollback, not arbitrary middle deletion. Removing an interior entry could invalidate every summary above it and requires a different data structure or recomputation. For comparison, two-sided scans combine saved left contributions with a separately accumulated right contribution.