Min Stack


155. Min Stack – LeetCode


Problem Statement

Design a stack that supports the following operations in constant time:


Examples

Example 1:

Input:
["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"]
[[], [-2], [0], [-3], [], [], [], []]

Output:
[null, null, null, null, -3, null, 0, -2]

Constraints


Intuition

To support getMin() in O(1) time, we need a way to track the minimum element at each point in the stack’s history.

The idea is to maintain a second stack (minStack) that always holds the minimum element so far corresponding to the top element of the main stack.


Approach: Two Stacks (Main + Min Stack)

  1. Maintain two stacks:

    • stack: Stores all pushed values.

    • minStack: Stores the minimum element at each level of the stack.

  2. On push(val):

    • Push val to stack.

    • Push min(val, minStack.peek()) to minStack.

  3. On pop():

    • Pop both stack and minStack.
  4. On top():

    • Return stack.peek().
  5. On getMin():

    • Return minStack.peek().

Java Code

class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

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

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

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

    public int getMin() {
        return minStack.peek();
    }
}

Time and Space Complexity

Operation Time Complexity Space Complexity
push O(1) O(n) (minStack)
pop O(1) O(1)
top O(1) O(1)
getMin O(1) O(1)

Dry Run

Input:

push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()

Stack States:

Operation stack minStack
push(-2) [-2] [-2]
push(0) [-2, 0] [-2, -2]
push(-3) [-2, 0, -3] [-2, -2, -3]
getMin() → -3
pop() [-2, 0] [-2, -2]
top() → 0
getMin() → -2

Conclusion

This is a classic stack design problem that uses an auxiliary min-tracking stack to achieve constant time operations for retrieving the minimum element.

It’s a useful pattern for designing custom data structures with enhanced operations.