Min Stack

Pattern: Min stack

medium

Store each value with the smallest value at or below it. getMin reads the minimum stored with the top. Popping restores the older minimum for free, since it is stored with the entry below.

The problem

Build MinStack with push(val), pop(), top() and getMin(), all O(1). pop, top and getMin are only called on a non-empty stack. Values cover the full 32-bit range.

Think first

  • What is wrong with one variable for the minimum?
  • When the minimum is popped, what should the new minimum be?
  • What could each entry remember?

Hints

    Brute force, and why it fails

    Scan the whole stack in getMin: O(n).

    The key insight

    The minimum of a stack only changes at the top, so storing a running minimum with each entry answers getMin from the top alone.

    Dry run

    stack(-2,-2) (0,-2) (-3,-3)

    push(-2): (-2, -2). push(0): (0, -2). push(-3): (-3, -3).

    Step 1 of 3

    The plan

    push(x): min = x if empty else min(x, top.min); push (x, min)
    pop():   pop
    top():   top.value
    getMin(): top.min
    

    Complexity

    Time
    O(1) per operation
    Space
    O(n)

    Each operation reads or writes the top entry only.

    Edge cases

    • Repeated minimums: each entry keeps its own copy, so popping one leaves the other.
    • Extreme 32-bit values.
    • A single item.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class MinStack {
        private final Deque<int[]> st = new ArrayDeque<>();   // each entry: {value, smallest value at or below it}
    
        public void push(int val) {
            int min = st.isEmpty() ? val : Math.min(val, st.peek()[1]);
            st.push(new int[]{val, min});
        }
    
        public void pop() {
            st.pop();
        }
    
        public int top() {
            return st.peek()[0];
        }
    
        public int getMin() {
            return st.peek()[1];                    // the minimum is stored with the top entry
        }
    }

    C++

    class MinStack {
    public:
        vector<pair<int, int>> st;                  // each entry: {value, smallest value at or below it}
    
        void push(int val) {
            int mn = st.empty() ? val : min(val, st.back().second);
            st.push_back(make_pair(val, mn));
        }
    
        void pop() {
            st.pop_back();
        }
    
        int top() {
            return st.back().first;
        }
    
        int getMin() {
            return st.back().second;                // the minimum is stored with the top entry
        }
    };

    Python

    class MinStack:
        def __init__(self):
            self.st = []                            # each entry: (value, smallest value at or below it)
    
        def push(self, val: int) -> None:
            mn = val if not self.st else min(val, self.st[-1][1])
            self.st.append((val, mn))
    
        def pop(self) -> None:
            self.st.pop()
    
        def top(self) -> int:
            return self.st[-1][0]
    
        def getMin(self) -> int:
            return self.st[-1][1]                   # the minimum is stored with the top entry

    Common mistakes

    • Comparing with the top's value instead of the top's minimum.
    • Java: comparing Integer objects with ==.

    Similar problems