CodeMosa

Master LeetCode Patterns

BeginnerStacks, Queues, HeapsRead Stacks, Queues, Heaps Fundamentals →

Min/Max Stack

Augment stack to support O(1) getMin/getMax or use a deque for window min/max

Time: O(1) ops
Space: O(n)

What is Min/Max Stack?

#
Definition: Keep running min/max alongside values to answer queries in O(1), or use a monotonic deque for window extrema.

Core Idea

#

Track running min/max alongside values or use monotonic deque for window extrema.

When to Use

#

Use for min stack design, and sliding window extrema in arrays.

How Min/Max Stack works

#

Augment each push with the running min/max to support O(1) queries; use a monotonic deque for window extrema.

  • O(1) min/max
  • Window extrema
  • Augmented push/pop

General Recognition Cues

#
General indicators that this pattern might be applicable
  • O(1) min/max
  • Window extrema
  • Augmented push/pop

Code Templates

#
Augment each push with the running min/max to support O(1) queries; use a monotonic deque for window extrema.
# Min/Max Stack Templates
class MinStack:
    def __init__(self):
        self.st=[]
    def push(self, x:int)->None:
        cur_min = x if not self.st else min(x, self.st[-1][1])
        self.st.append((x, cur_min))
    def pop(self)->None:
        self.st.pop()
    def top(self)->int:
        return self.st[-1][0]
    def getMin(self)->int:
        return self.st[-1][1]

Pattern Variants & Approaches

#
Different methodologies and implementations for this pattern
1

O(1) Min Stack

#

Maintain paired min with each push

When to Use This Variant
  • getMin() O(1)
Use Case
Design min stack
Advantages
  • Fast queries
  • Simple
Implementation
class MinStack:
    def __init__(self): self.st=[]
    def push(self, x): self.st.append((x, x if not self.st else min(x, self.st[-1][1])))
    def pop(self): self.st.pop()
    def top(self): return self.st[-1][0]
    def getMin(self): return self.st[-1][1]
2

Monotonic Queue

#

Deque for window min/max

When to Use This Variant
  • Window size k
Use Case
Sliding extrema
Advantages
  • Linear time
  • Compact
Implementation
from collections import deque
class MonotonicQueue:
    def __init__(self): self.dq = deque()
    def push(self, x):
        while self.dq and self.dq[-1] < x: self.dq.pop()
        self.dq.append(x)
    def pop(self, x):
        if self.dq and self.dq[0] == x: self.dq.popleft()
    def max(self): return self.dq[0] if self.dq else None

Common Pitfalls

#
Watch out for these common mistakes
  • Syncing aux stack with main
  • Handling duplicates correctly

Example Problems

#
Classic LeetCode problems using this pattern

Complexity Analysis

#
Time Complexity
O(1) ops

Each operation is O(1).

Space Complexity
O(n)

Stack/deque holds elements.

Ready to test your knowledge?

Test your pattern recognition with interactive questions