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.

5 variations · 7 problems · 5 with animated walkthroughs

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

Stack
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
}

The variations

  1. 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. popMax also needs to remove from the middle, so pair the stack with a sorted map or heap and delete lazily.

    Now you solve
  2. 2Lazy updates

    Instead of adding val to 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.

  3. 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.

  4. 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.

  5. 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 popMax with a plain stack is O(n); use a sorted structure plus lazy deletion, or a doubly linked list with a sorted map.
Next: Queues and ring buffers: fixed windows and streams →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.