ToolMight Logo
MediumStackAuxiliary Min TrackingDesign

Min Stack

Design a LIFO stack supporting push, pop, top, and getMin in O(1) time. Compare a synchronized parallel min stack against a sparse minimum-change stack.

Optimal Time
O(1) for all operations
Optimal Space
O(n)
Primary Pattern
Auxiliary Min Tracking
Visualizer
Open Interactive View →

Problem Statement

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

You must implement a solution with O(1) time complexity for each function.

Examples & Constraints

Example 1
Input: ["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]
Explanation: minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3\nminStack.pop(); minStack.top(); // return 0\nminStack.getMin(); // return -2
Constraints
  • -2^31 <= val <= 2^31 - 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Whenever a LIFO stack must answer prefix aggregates (min, max) in O(1) time across pops, store the aggregate state per stack height or push onto a monotonic auxiliary stack.

Core Invariant

Because stack removals only occur at the top, the minimum of elements below depth k never changes while depth >= k remains intact.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Paired Auxiliary Min StackOptimal
O(1) for all operationsO(n)Maintain two parallel stacks: a primary data stack and an auxiliary min stack that records the running minimum value associated with each stack depth in O(1) time.
2. Sparse Auxiliary Min Stack (Deduplicated Minimums)Optimal
O(1) for all operationsO(n) worst-case, much smaller in practicePush onto the auxiliary minStack only when the incoming value is less than or equal to the current minimum, saving memory on non-decreasing workloads.

1. Paired Auxiliary Min Stack

Optimal
TimeO(1) for all operations
SpaceO(n)

Maintain two parallel stacks: a primary data stack and an auxiliary min stack that records the running minimum value associated with each stack depth in O(1) time.

Time ComplexityO(1) for all operations

push, pop, top, and getMin all execute in constant O(1) time without any loops or traversals.

Space ComplexityO(n)

Consumes 2N space to store N primary elements and N associated running minimums.

How It Works

The Invariant: Every Stack Level Remembers Its Minimum

A normal stack easily provides O(1) push, pop, and top. The challenge is getMin():

  • Scanning the stack takes O(n) time.
  • If we only keep a single global variable currentMin, when that minimum is popped off, we cannot know what the previous minimum was without scanning the entire remaining stack!

The Solution: History Tracking

Because stack operations strictly adhere to Last-In, First-Out (LIFO) ordering, the minimum of any prefix of the stack never changes as long as those elements remain in the stack!

  1. Maintain two stacks:
  • dataStack: Stores normal values.
  • minStack: Stores the running minimum up to the current height.
  1. Push(val):
  • Push val onto dataStack.
  • The new minimum is min(val, minStack.top()) (or val if minStack is empty).
  • Push this new minimum onto minStack.
  1. Pop():
  • Pop simultaneously from both dataStack and minStack.
  • The previous minimum is naturally restored at the top of minStack!
  1. Top(): Return dataStack.top().
  2. GetMin(): Return minStack.top() in instant O(1) time.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1push(-2)

dataStack: [-2], minStack: [-2]. Current min = -2.

State:data: [-2]min: [-2]
Strengths
  • +Guaranteed constant O(1) time for every operation
  • +Simple and bug-resistant without integer-encoding math
Trade-offs
  • -Always duplicates every element in minStack even when items are strictly increasing

Reference Implementation

Complete implementation for Paired Auxiliary Min Stack in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
else:
self.min_stack.append(self.min_stack[-1])
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def get_min(self) -> int:
return self.min_stack[-1]
if __name__ == "__main__":
ms = MinStack()
ms.push(-2)
ms.push(0)
ms.push(-3)
print("Min:", ms.get_min()) # -3
ms.pop()
print("Top:", ms.top()) # 0
print("Min:", ms.get_min()) # -2

2. Sparse Auxiliary Min Stack (Deduplicated Minimums)

Optimal
TimeO(1) for all operations
SpaceO(n) worst-case, much smaller in practice

Push onto the auxiliary minStack only when the incoming value is less than or equal to the current minimum, saving memory on non-decreasing workloads.

Time ComplexityO(1) for all operations

Every method performs at most two O(1) stack push/pop/peek calls.

Space ComplexityO(n) worst-case, much smaller in practice

Takes O(1) auxiliary space when pushed values trend upward, and O(n) only on strictly decreasing sequences.

How It Works

Recording Only Minimum Transitions

Instead of pushing a copy on every single push, we only push to minStack when a new value becomes <= minStack.top():

  1. `push(val)`: Always push val to dataStack. Push val to minStack if `minStack` is empty OR `val <= minStack.top()`.
  2. `pop()`: Pop removed = dataStack.pop(). If removed == minStack.top(), also pop minStack.
  3. Why `<=` (not strict `<`) matters: Suppose we push -2, then push -2 again. Both copies must appear in minStack so popping the first -2 leaves the second -2 intact for getMin().

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1push(5), then push(8), then push(10)

5 enters minStack; 8 and 10 are > 5 so minStack stays size 1.

State:data: [5, 8, 10]min: [5]
Strengths
  • +Still O(1) worst-case time across all 4 methods
  • +Saves auxiliary memory whenever incoming values stay above current min
Trade-offs
  • -Requires remembering <= rather than < for duplicate minimums
  • -In Java, Integer.equals() or unboxed int comparisons avoid object reference bugs above 127

Reference Implementation

Complete implementation for Sparse Auxiliary Min Stack (Deduplicated Minimums) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class SparseMinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def get_min(self) -> int:
return self.min_stack[-1]
Interactive Visualizer

Trace Stack mechanics in memory

Step through custom inputs in the Stack visualizer to inspect pointer updates, array shifts, and call-stack state alongside Min Stack.

Open Stack visualizer

Frequently Asked Questions

Why cannot a single variable track the minimum?

A single variable tracks the current minimum while pushing, but once pop() removes that minimum, you have no way to recover the previous minimum without scanning remaining items in O(n).

In the sparse min stack, why must we check `val <= minStack.top()` instead of `<`?

If the current minimum appears twice (e.g. pushing -2 twice) and you only record strict <, popping the first -2 pops the only -2 in minStack, leaving getMin() wrong.

Watch out for Java Integer caching when comparing `stack.peek()` and `minStack.peek()`

Comparing two boxed Integer objects with == checks reference identity outside -128..127. Always unbox (int val = stack.pop();) or use .equals() in Java.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Duplicate minimum values (e.g., push(-2), push(-2), pop(), getMin()) must still return -2.
  • Values hitting full signed 32-bit extremes (-2^31 to 2^31 - 1) can overflow subtraction-encoding tricks unless 64-bit integers or dual stacks are used.
  • Alternating dips and peaks where pop removes the sole minimum and exposes an older minimum.

Common Bugs to Avoid

  • Using strict `<` instead of `<=` when pushing onto a sparse minStack — popping one copy of a duplicate minimum then drops the active minimum prematurely.
  • Using signed 32-bit `val - min` encoding without promoting to 64-bit ints, causing signed overflow on `INT_MIN`.
  • Tracking only a single scalar `minVal`, which forces an O(n) scan whenever `pop()` removes the minimum.

Interview Follow-Up Variations

  • O(1) Single-Stack Delta Encoding: store `val - min` in 64-bit integers (`long long`) to eliminate auxiliary stack memory entirely.
  • Max Stack (with `popMax()`): combine a doubly-linked list with a TreeMap or lazy-deletion Max-Heap for O(log n) `popMax()`.

Related Problems

All problems
EasyStack

Valid Parentheses

Check whether brackets (), {}, and [] match in proper nested LIFO order. Compare iterative innermost-pair collapse against O(n) stack validation.

Pattern: Last-In First-Out (LIFO)
O(n) · O(n)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve