Min Stack

Build a stack that can tell you its smallest value at any moment, in constant time.

Design a stack of integers with four operations. push(val) puts a value on top, pop() removes the top value, and top() returns the top value without removing it. getMin() returns the smallest value in the stack. Each operation must take constant time, O(1), however many values the stack holds. pop, top and getMin are only called when the stack is not empty.

Example 1
Input: push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
Output: getMin() = -3, top() = 0, getMin() = -2
Solution

The Idea

A stack works like a pile of plates. You put a new plate on top and take plates off the top, and the plates underneath are never touched. Pushing adds to the top, popping removes the top, and top() looks at it.

Follow the example. After push(-2), push(0) and push(-3), the pile holds -2, 0 and -3, from the bottom up, and the smallest is -3. Keeping one variable for the smallest value seems enough: each push compares the new value with it, so the variable goes -2, -2, -3.

Then pop() removes -3. What is the smallest value now? The variable still says -3, which has left the stack. The right answer, -2, is buried somewhere below, and finding it means looking at every value, which takes longer the bigger the stack. So how can getMin() know the answer after a pop without searching?

Think about what a pop can change. It only removes the top, so while an entry stays on the stack, the entries under it stay exactly the same. That means the smallest value among an entry and everything under it, call it the entry's smallest so far, never changes while the entry is there. We can work it out once, when the entry is pushed, and store it next to the value.

Look at the picture below. Each row is one entry, with its value on the left and its smallest so far on the right.

Each stack entry holds a value and the smallest value so far. After push(-3) the top entry is -3 with smallest so far -3. After pop() the new top is 0, whose smallest so far is -2.

In the stack labelled "after push(-3)", the bottom entry -2 has smallest so far -2, since nothing is under it. The entry 0 also has -2, because -2 is under it. The top entry -3 has -3, and getMin() simply reads that from the top.

Now follow the pop() arrow to the stack labelled "after pop()". The new top is 0, and its smallest so far is -2, which is exactly the right answer for the two values left. Nothing had to be searched or recomputed: the answer was stored with 0 when 0 was pushed.

Solution Approach

Turning that idea into code means settling three things: what each entry holds, how push works out the smallest so far, and what pop, top and getMin are left to do.

What each entry holds

What does one entry need to carry? Two numbers: the value and its smallest so far. A small array int[] {val, min} holds them together. The entries go into an ArrayDeque, a class in java.util that keeps its elements in a growable array. Its push, pop and peek methods all work on the same end, which serves as the top.

Working out the smallest so far on push

How does push find the new entry's smallest so far without looking through the stack? It only needs the entry directly underneath, the current top. That entry already knows the smallest value of everything below, so the new entry's smallest so far is the smaller of the new value and the top's smallest so far.

On an empty stack there is no entry underneath, so the smallest so far is the value itself. A value pushed twice is no special case either: each copy gets its own entry and its own smallest so far, so popping one copy leaves the other with the same minimum.

Reading and removing the top

What is left for the other three operations? Each one touches only the top entry. top() returns its value, getMin() returns its smallest so far, and pop() removes it. After a pop, the entry that becomes the top already holds the right smallest so far for the values still on the stack, so nothing needs updating.

Java Solution

The class has five parts, one for the storage and one for each operation:

  • stack: an ArrayDeque of entries, each an int[] holding the value and its smallest so far.
  • push(val): works out min, the new entry's smallest so far, from val and the top entry's peek()[1], then pushes {val, min}.
  • pop(): removes the top entry.
  • top(): returns the top entry's value, peek()[0].
  • getMin(): returns the top entry's smallest so far, peek()[1].

The main method runs the example, pushes the same smallest value twice and pops one copy, puts a bigger value on top of the minimum, and empties a stack before pushing again.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class MinStack {
    // each entry: {value, smallest value at or below this entry}
    private final Deque<int[]> stack = new ArrayDeque<>();

    public void push(int val) {
        int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
        stack.push(new int[] {val, min});
    }

    public void pop() {
        stack.pop();
    }

    public int top() {
        return stack.peek()[0];
    }

    public int getMin() {
        return stack.peek()[1];
    }

    public static void main(String[] args) {
        MinStack s = new MinStack();
        s.push(-2);
        s.push(0);
        s.push(-3);
        System.out.println("getMin() = " + s.getMin());
        s.pop();
        System.out.println("top() = " + s.top() + ", getMin() = " + s.getMin());

        MinStack d = new MinStack();             // the smallest value pushed twice
        d.push(1);
        d.push(1);
        d.pop();
        System.out.println("after push(1), push(1), pop(): getMin() = " + d.getMin());

        MinStack u = new MinStack();             // a bigger value on top of the minimum
        u.push(3);
        u.push(7);
        System.out.println("after push(3), push(7): top() = " + u.top()
            + ", getMin() = " + u.getMin());
        u.pop();
        u.pop();
        u.push(9);
        System.out.println("after both pops and push(9): getMin() = " + u.getMin());
    }
}

Running it prints:

Output
getMin() = -3
top() = 0, getMin() = -2
after push(1), push(1), pop(): getMin() = 1
after push(3), push(7): top() = 7, getMin() = 3
after both pops and push(9): getMin() = 9

The example's answers, -3, then 0 and -2, appear in the opening two lines. Look at top() = 0, getMin() = -2: right after pop() removed -3, the minimum went back to -2, read straight from the entry for 0.

In the third line, one copy of 1 was popped, and getMin() still gives 1 because the other copy keeps its own smallest so far. The fourth line shows 7 on top while getMin() stays 3, since the entry for 7 stored the smaller of 7 and 3. In the last line, the stack was emptied before push(9), so 9 became its own smallest so far, and the old 3 is gone.

The original implementation, MinStack.java, is on GitHub.

Complexity

Every operation looks only at the top entry, so none of them gets slower as the stack grows.

  • Time: O(1) for every operation, because push makes one comparison with the top's smallest so far and adds one entry, and pop, top and getMin each touch only the top entry. Now and then ArrayDeque copies its entries into a bigger array, but spread over all the pushes that still costs a constant amount per push.
  • Space: O(n) for n values on the stack, because each value is stored together with its smallest so far: two numbers per value instead of one, which still grows in step with n.

A stack that can also remove its largest value from wherever it sits, not just read the smallest, takes more work; see Max Stack.