Skip to lesson

Min stack and a queue from stacks

Classic interview problems test stack composition: retrieving the minimum in O(1) time, and building a queue from stacks.

Min stack with O(1) getMin retrieval

A plain stack cannot report its minimum without scanning every element. A second stack, minStack, stores the running minimum at every depth, so getMin is O(1).

  1. When pushing x, push x to primary stack.
  2. If minStack is empty, push x to minStack; otherwise push Math.min(x, minStack.peek()).
  3. When popping, pop from both primary stack and minStack.
  4. getMin returns minStack.peek() in O(1) time.

push(5), push(3), push(7), getMin(), pop()

Step 1 of 7

5 3 7.
main stack(empty)
minStack(empty)
Two stacks start empty: the main stack and minStack. The tokens above are the values we will push.

Example 1 · Brute force: scan the whole stack for the minimum (O(n) getMin, O(1) extra space)

MinStackScanDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class MinStackScanDemo {    static class ScanMinStack {        private final Deque<Integer> stack = new ArrayDeque<>();
        void push(int val) { stack.push(val); }        void pop() { stack.pop(); }        int top() { return stack.peek(); }
        int getMin() {            int min = Integer.MAX_VALUE;            for (int x : stack) {                min = Math.min(min, x);            }            return min;        }    }
    public static void main(String[] args) {        ScanMinStack ms = new ScanMinStack();        ms.push(-2);        ms.push(0);        ms.push(-3);        System.out.println("Min: " + ms.getMin());        ms.pop();        System.out.println("Top: " + ms.top());        System.out.println("Min: " + ms.getMin());    }}
Output
Min: -3
Top: 0
Min: -2

What this code does

  • push, pop and top are O(1), but getMin visits every element each time it is called: O(n).
  • With 100,000 items and 100,000 getMin calls this is about 10 billion steps.
  • The parallel minimum stack in the next example stores the answer for every depth, so getMin becomes O(1).

Example 2 · Optimal: parallel minimum stack (O(1) getMin, O(n) extra space)

MinStackDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class MinStackDemo {    static class MinStack {        private final Deque<Integer> stack = new ArrayDeque<>();        private final Deque<Integer> minStack = new ArrayDeque<>();
        public void push(int val) {            stack.push(val);            if (minStack.isEmpty() || val <= minStack.peek()) {                minStack.push(val);            } else {                minStack.push(minStack.peek());            }        }
        public void pop() {            stack.pop();            minStack.pop();        }
        public int top() { return stack.peek(); }        public int getMin() { return minStack.peek(); }    }
    public static void main(String[] args) {        MinStack ms = new MinStack();        ms.push(-2);        ms.push(0);        ms.push(-3);        System.out.println("Min: " + ms.getMin());        ms.pop();        System.out.println("Top: " + ms.top());        System.out.println("Min: " + ms.getMin());    }}
Output
Min: -3
Top: 0
Min: -2

What this code does

  • Pushing -3 updates the minimum to -3.
  • Popping -3 restores the previous minimum of -2.
  • Both getMin and top execute in O(1) time.

Example 3 · Space-Optimized Min Stack with Single Stack of Pairs

PairMinStackDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class PairMinStackDemo {    static class Element {        int val, min;        Element(int val, int min) { this.val = val; this.min = min; }    }
    static class PairMinStack {        private final Deque<Element> stack = new ArrayDeque<>();
        public void push(int val) {            int currentMin = stack.isEmpty() ? val : Math.min(val, stack.peek().min);            stack.push(new Element(val, currentMin));        }
        public int pop() { return stack.pop().val; }        public int getMin() { return stack.peek().min; }    }
    public static void main(String[] args) {        PairMinStack pms = new PairMinStack();        pms.push(15);        pms.push(10);        pms.push(20);        System.out.println("Current min: " + pms.getMin());    }}
Output
Current min: 10

What this code does

  • Each stack element packages its value and the minimum at that point.
  • Avoids managing two separate stack data structures.
  • All operations take O(1) time.

A single min variable fails on pop, because the previous minimum is forgotten. With minStack, every push stores min(x, minStack.peek()) and every pop removes from both stacks, so minStack.peek() is always the minimum of what remains.

Queue implementation using two stacks

A stack is Last-In First-Out. Reversing a LIFO sequence produces First-In First-Out order. We use two stacks named inStack and outStack. Moving elements on every push would make push take O(n) time, so we transfer lazily.

Example 4 · Queue Built from Two Stacks

QueueUsingStacksDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class QueueUsingStacksDemo {    static class MyQueue {        private final Deque<Integer> in = new ArrayDeque<>();        private final Deque<Integer> out = new ArrayDeque<>();
        public void push(int x) { in.push(x); }
        public int pop() {            move();            return out.pop();        }
        public int peek() {            move();            return out.peek();        }
        public boolean empty() { return in.isEmpty() && out.isEmpty(); }
        private void move() {            if (out.isEmpty()) {                while (!in.isEmpty()) {                    out.push(in.pop());                }            }        }    }
    public static void main(String[] args) {        MyQueue q = new MyQueue();        q.push(10);        q.push(20);        System.out.println("Peek: " + q.peek());        System.out.println("Pop: " + q.pop());        q.push(30);        System.out.println("Pop: " + q.pop());        System.out.println("Empty: " + q.empty());    }}
Output
Peek: 10
Pop: 10
Pop: 20
Empty: false

What this code does

  • move() transfers 10 and 20 into out stack in reversed order.
  • 10 is popped first, preserving FIFO order.
  • Pushing 30 goes into in without disturbing out.

push(x) always goes straight into inStack in O(1). pop() removes the top of outStack; when outStack is empty, first move every item from inStack to outStack, which reverses them into first-in first-out order.

Trace of push(1), push(2), pop(), push(3), pop():

  • push(1), push(2): inStack [1, 2], outStack empty.
  • pop(): outStack is empty, so transfer; outStack becomes [2, 1] with 1 on top, and pop returns 1.
  • push(3): inStack [3]; outStack still holds [2].
  • pop(): outStack is not empty, so pop it directly; returns 2.

Key rules:

  • inStack: receives new incoming elements on push.
  • outStack: serves outgoing elements on pop and peek.
  • Transfer rule: transfer from in to out only when outStack is completely empty.

Order of execution

Order the steps of pop()

Tap the steps in the order a pop() on the two-stack queue runs.

Never transfer from inStack if outStack already holds elements. Doing so would violate FIFO arrival order.

Understanding amortized O(1) time complexity

Amortized O(1) means the average cost per operation over a whole sequence is constant, even if a single call is occasionally expensive.

A single pop() call might transfer n elements from inStack to outStack, taking O(n) time.

However, each element enters inStack once, moves to outStack once, and leaves outStack once. That is exactly 3 operations per element over its entire lifetime.

Across n total operations, the aggregate work is O(n). Therefore, the average (amortized) cost per operation is strictly O(1).

  • Worst-case single step: O(n) during bulk transfer.
  • Lifetime cost per element: 1 push + 1 transfer + 1 pop = 3 operations.
  • Amortized complexity: O(1) on average across all operations.

Next step

Check your understanding

10 quick questions