Min Stack (LeetCode 155): Solution and Explanation

Medium
Stack
Design

Design a stack that supports push, pop and top, plus a getMin operation that returns the smallest element currently in the stack. Every operation must run in constant time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A plain stack already gives you push, pop and top in constant time. The challenge is getMin. The naive version scans the whole stack on every call, which is O(n). Keeping a single variable for the current minimum is the next idea, and it works for pushes, but it breaks on pops: if you pop the element that was the minimum, you have no idea what the previous minimum was without rescanning.

The key observation is that a stack only ever changes at the top. So the minimum of the stack is fully determined by its depth. When the stack has three elements, its minimum is the minimum of those three, and that does not change until the third element is popped. If you remember the minimum for every depth, a pop simply reverts to the minimum for the previous depth.

That is exactly what the second stack, minStack, stores. Every time you push a value, you also push the minimum of that value and the current top of minStack. Every time you pop, you pop both stacks together. The top of minStack is then always the minimum of everything currently in the main stack.

The cost is extra memory, one additional entry per element, but every operation becomes a constant number of list operations. It is a small, clean example of trading space for time by caching a running aggregate alongside the data.

Approach: Two stacks with running minimum

  1. Initialize two empty lists, stack for values and minStack for the running minimum.
  2. In push(val), append val to stack, then append min(val, minStack[-1]) to minStack, or just val when minStack is empty.
  3. In pop(), pop from both stacks so their depths stay aligned.
  4. In top(), return stack[-1].
  5. In getMin(), return minStack[-1], the minimum at the current depth.

Step-by-step example

push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
  1. push(-2): stack = [-2] and minStack = [-2].
  2. push(0): the minimum of 0 and -2 is -2, so stack = [-2, 0] and minStack = [-2, -2].
  3. push(-3): the minimum of -3 and -2 is -3, so stack = [-2, 0, -3] and minStack = [-2, -2, -3]. getMin() returns -3.
  4. pop(): both stacks lose their top, giving stack = [-2, 0] and minStack = [-2, -2].
  5. top() returns 0 and getMin() returns -2, the correct minimum after -3 was removed.

Code: Python, Java, C++

1class MinStack:
2    def __init__(self):
3        self.stack = []
4        self.minStack = []
5
6    def push(self, val: int) -> None:
7        self.stack.append(val)
8        val = min(val, self.minStack[-1] if self.minStack else val)
9        self.minStack.append(val)
10
11    def pop(self) -> None:
12        self.stack.pop()
13        self.minStack.pop()
14
15    def top(self) -> int:
16        return self.stack[-1]
17
18    def getMin(self) -> int:
19        return self.minStack[-1]

Time and space complexity

Time

O(1)

Each operation performs a constant number of list appends, pops or index reads, all amortized O(1).

Space

O(n)

The min stack stores one entry for every element in the main stack, so memory is about twice that of a plain stack.

Other approaches

Min stack that only grows on new minimums (time O(1), space O(n))

Push onto minStack only when the new value is less than or equal to its top, and pop from it only when the popped value equals its top. It saves memory when the minimum rarely changes, but you must keep the <= comparison to handle duplicates.

Single stack with encoded differences (time O(1), space O(n))

Store the difference between each value and the current minimum, and update the minimum when a negative difference appears. It uses only one stack and one variable, but the arithmetic is error prone and can overflow in fixed-width integers.

Common mistakes

  • Tracking the minimum in a single variable, which cannot recover the previous minimum after the current minimum is popped.
  • Popping only from the main stack, which leaves minStack out of sync and returns stale minimums.
  • In the space-saving variant, pushing to the min stack only on strictly smaller values. A duplicate minimum then gets lost when one copy is popped.
  • Reading minStack[-1] without checking whether it is empty during the very first push.

Frequently asked questions

How do you get the minimum of a stack in O(1) time?

Keep a second stack where each entry is the minimum of all values at or below that depth. The top of that stack is always the current minimum, and popping both stacks together keeps it correct.

Can Min Stack be implemented with only one stack?

Yes. You can push pairs of (value, current minimum) onto a single stack, which is the same idea in one structure. You can also encode differences from the minimum to avoid the extra field.

What is the space complexity of Min Stack?

It is O(n), since the auxiliary stack holds one minimum per element. The optimized variant can use less in practice but is still O(n) in the worst case.

Why does popping work correctly?

The minimum at each depth depends only on the elements at or below it. Removing the top element exposes the previous depth, whose minimum was already recorded.