#155

Min Stack

Medium
StackDesignStackAuxiliary Data Structures
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(n)
O(n)
💡

Intuition

Time O(1)Space O(n)

To achieve O(1) time complexity for getMin, we can use an auxiliary stack to keep track of the minimum values. Every time we push a new value, we also push the current minimum onto this auxiliary stack.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two stacks: one for the actual values and one for the minimum values.
  2. 2Step 2: When pushing a value, compare it with the current minimum and push the smaller one onto the min stack.
  3. 3Step 3: For pop, remove the top elements from both stacks.
  4. 4Step 4: For getMin, simply return the top of the min stack.
solution.py21 lines
1class MinStack:
2    def __init__(self):
3        self.stack = []
4        self.min_stack = []
5    
6    def push(self, val: int) -> None:
7        self.stack.append(val)
8        if not self.min_stack or val <= self.min_stack[-1]:
9            self.min_stack.append(val)
10    
11    def pop(self) -> None:
12        if self.stack:
13            val = self.stack.pop()
14            if val == self.min_stack[-1]:
15                self.min_stack.pop()
16    
17    def top(self) -> int:
18        return self.stack[-1] if self.stack else None
19    
20    def getMin(self) -> int:
21        return self.min_stack[-1] if self.min_stack else None

Complexity note: All operations (push, pop, top, getMin) run in O(1) time because we only access the top of the stacks. The space complexity is O(n) due to the additional stack for minimum values.

  • 1Using an auxiliary stack allows us to keep track of the minimum value efficiently.
  • 2Both stacks maintain a relationship where the min stack always has the current minimum at the top.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.