Design Data Structures · Pattern 3 of 10
Stack designs: min stack, frequency stack, text editor
A stack can remember extra facts about everything below each item, like the minimum so far. Store that fact with the item when you push, and it is still correct when you pop back to it.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- A stack that also answers min, max or most frequent in O(1)
- Change many items at once (increment the bottom k)
- A cursor that moves through text, with typing and deleting
- Walk a nested structure lazily, one item at a time
The template
class MinStack {
Deque<int[]> st = new ArrayDeque<>(); // {value, min of this item and everything below}
void push(int val) {
int min = st.isEmpty() ? val : Math.min(val, st.peek()[1]);
st.push(new int[]{val, min});
}
void pop() { st.pop(); }
int top() { return st.peek()[0]; }
int getMin() { return st.peek()[1]; } // the min is stored with the top
} class MinStack:
def __init__(self):
self.st = [] # (value, min of this item and everything below)
def push(self, val):
m = min(val, self.st[-1][1]) if self.st else val
self.st.append((val, m))
def pop(self):
self.st.pop()
def top(self):
return self.st[-1][0]
def getMin(self):
return self.st[-1][1] # the min is stored with the top class MinStack {
vector<pair<int, int>> st; // {value, min of this item and everything below}
public:
void push(int val) {
int m = st.empty() ? val : min(val, st.back().second);
st.push_back({val, m});
}
void pop() { st.pop_back(); }
int top() { return st.back().first; }
int getMin() { return st.back().second; } // the min is stored with the top
}; class MinStack {
constructor() { this.st = []; } // [value, min of this item and everything below]
push(val) {
const m = this.st.length ? Math.min(val, this.st[this.st.length - 1][1]) : val;
this.st.push([val, m]);
}
pop() { this.st.pop(); }
top() { return this.st[this.st.length - 1][0]; }
getMin() { return this.st[this.st.length - 1][1]; } // the min is stored with the top
} The variations
-
1Remember a fact with every item
Push the value together with the min (or max) of the stack at that point. The top always knows the answer, and popping restores the previous answer for free.
popMaxalso needs to remove from the middle, so pair the stack with a sorted map or heap and delete lazily.Now you solve- Max Stack Hard Stuck? solution
-
2Lazy updates
Instead of adding
valto the bottom k items now, add it to a side array at index k − 1. When that item is popped, return its value plus the pending amount and pass the amount down to the item below. -
3A stack per frequency
Count each value, and keep a stack for every frequency level. A value pushed for the third time goes on stack 3. Pop from the highest level; ties go to the most recent push automatically.
-
4Two stacks around a cursor
Everything left of the cursor is one stack, everything right of it is another (stored reversed). Typing pushes left, deleting pops left, and moving the cursor pops from one and pushes to the other. Each step is O(1) per character moved.
Now you solve -
5A stack as a lazy iterator
Push the list's items in reverse. In
hasNext, while the top is a nested list, pop it and push its items in reverse. Only the part you actually read gets expanded.
Mistakes to avoid
- Keeping one global minimum: after popping it, you do not know the next one. Store the min per level.
- Increment on the bottom k by looping: store the pending increment at index k − 1 and pass it down on pop.
- Max stack
popMaxwith a plain stack is O(n); use a sorted structure plus lazy deletion, or a doubly linked list with a sorted map.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.