Min Stack

Design a stack that supports retrieving the minimum element in O(1).

Pattern

Auxiliary Stack

This problem follows the Auxiliary Stack pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Maintain a parallel stack that tracks the current minimum at each level.

Key Insight

The min stack only grows when a new minimum is seen — it mirrors the main stack's minimum at each depth level.

Step-by-step

  1. 1Use two stacks: one main stack and one to track minimums
  2. 2On push: push to main stack; push to min stack if value <= current min
  3. 3On pop: pop from main stack; pop from min stack if the popped value equals the min
  4. 4getMin returns the top of the min stack

Pseudocode

class MinStack:
    def __init__(self):
        self.stack = []
        self.minStack = []
    
    def push(self, val):
        self.stack.append(val)
        if not self.minStack or val <= self.minStack[-1]:
            self.minStack.append(val)
    
    def pop(self):
        val = self.stack.pop()
        if val == self.minStack[-1]:
            self.minStack.pop()
    
    def getMin(self):
        return self.minStack[-1]
Complexity Analysis

Time Complexity

O(1)

Space Complexity

O(n)
More Stack Problems

Master this pattern with YeetCode

Practice Min Stack and similar Stack problems with flashcards. Build pattern recognition through active recall.

Practice this problem