Sub topic 15
A stack that returns its minimum in constant time
This chapter assumes you can write a stack with a Python list, read Big-O notation, and know that push, pop, and peek each cost O(1) on an array-backed stack.
The problem
Suppose you need a stack that also answers "what is the smallest value currently stored?" A direct approach scans every item, which costs O(n) per query. You can do better. The goal is a stack where push, pop, and minimum all run in O(1).
Tracking a single min variable fails. When you pop the current minimum, you must know the next smallest value, and a single variable has forgotten it.
The idea: remember the minimum at every depth
The minimum of a stack depends only on the items below and including the top. So you can store the minimum alongside each item at the moment it is pushed. When an item is removed, the stored minimum for the items beneath it is still correct.
A second stack does this job. It always has the same height as the main stack. Entry i of the second stack holds the minimum of main-stack entries 0 through i.
class MinStack:
def __init__(self):
self._items = []
self._mins = []
def push(self, x):
self._items.append(x)
current_min = x if not self._mins else min(x, self._mins[-1])
self._mins.append(current_min)
def pop(self):
self._mins.pop()
return self._items.pop()
def minimum(self):
return self._mins[-1]Each push compares the new value with the current minimum on top of _mins and pushes the smaller one. Each pop removes the top of both stacks together, so they never get out of step.
Tracing an example
Push 5, 3, 7, 3 and then pop twice.
| Operation | `_items` | `_mins` | `minimum()` |
|---|---|---|---|
| push 5 | [5] | [5] | 5 |
| push 3 | [5, 3] | [5, 3] | 3 |
| push 7 | [5, 3, 7] | [5, 3, 3] | 3 |
| push 3 | [5, 3, 7, 3] | [5, 3, 3, 3] | 3 |
| pop | [5, 3, 7] | [5, 3, 3] | 3 |
| pop | [5, 3] | [5, 3] | 3 |
Pushing a duplicate minimum (the second 3) matters. Because _mins gets an entry for every push, popping one 3 does not lose the other.
Cost
| Operation | Time | Extra space |
|---|---|---|
| `push` | O(1) amortized | one entry in `_mins` |
| `pop` | O(1) | none |
| `minimum` | O(1) | none |
The price is O(n) extra space, because _mins is as tall as _items. This is the usual trade: spend memory to make a query fast.
Common errors
- Calling
minimumorpopon an empty stack.self._mins[-1]raises a bareIndexError. The version above is deliberately short. In production code, check for emptiness first and raise a clear message, as in the earlier error-handling chapter. - Updating only one stack. If
popremoves from_itemsbut not_mins, laterminimum()calls return stale values. - Using
<instead ofminwhen you skip duplicates. A common space optimization pushes onto_minsonly when a new value is less than or equal to the current minimum. It must use<=. With<, popping one of two equal minimums would remove the only record of that value.
Exercise
Starting from an empty MinStack, you push 4, 2, 6, 1 and then pop once. What does minimum() return, and what does _mins contain?
Show answer
After the pop, items is [4, 2, 6] and mins is [4, 2, 2], so minimum() returns 2. Popping the 1 also removed the matching top entry of _mins, which restores the earlier minimum.
Exercise
Why can't a single variable named minsofar replace the second stack?
Show answer
When the current minimum is popped, the stack needs the next smallest value among the remaining items. A single variable keeps only one value, so it cannot restore the previous minimum without scanning all the items, which costs O(n).