Skip to content
mlmentorship

Min Stack

Build a stack that returns its current minimum in constant time.

Published · 10 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Min Stack

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Calls to push(value), pop(), top(), and get_min() on an initially empty MinStack of integers. Output. top returns the newest remaining value, and get_min returns the smallest remaining value. The pop operation removes the newest value without returning it. Rules. Equal minima are separate entries and must survive removal of another equal entry. Minimum queries must not scan the stack. Calls to pop, top, or get_min require a nonempty stack. Empty calls raise IndexError in the reference. Example. After push(5), push(2), and push(4), top() returns 4 and get_min() returns 2. After one pop(), both queries return 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Store each value with the minimum for its entire stack prefix, so the top pair always answers get_min().

Problem trace

Each stack entry remembers the minimum that existed beneath it

Worked example: duplicate minima need duplicate historical statePushing 5,2,2 stores minima 5,2,2. Popping one 2 must leave minimum 2; recording only distinct minima would incorrectly restore 5.Each value owns its ownminimum-so-far snapshotBefore popvalue | min552222After onepopvalue | min5522The surviving top pair is still valuetwo / minimum two.
Read it this way: Pushing 5,2,2 stores minima 5,2,2. Popping one 2 must leave minimum 2; recording only distinct minima would incorrectly restore 5. After popping one two, which surviving snapshot still establishes minimum two?
Full interview answer 10 min read
Reading depth

Maintain a stack that can report both its newest value and its smallest current value.

Problem

Input. Calls to push(value), pop(), top(), and get_min() on an initially empty MinStack of integers.

Output. top returns the newest remaining value, and get_min returns the smallest remaining value. The pop operation removes the newest value without returning it.

Rules. Equal minima are separate entries and must survive removal of another equal entry. Minimum queries must not scan the stack. Calls to pop, top, or get_min require a nonempty stack. Empty calls raise IndexError in the reference.

Example. After push(5), push(2), and push(4), top() returns 4 and get_min() returns 2. After one pop(), both queries return 2.

Picture: Each Level Saves Its Own Answer

Problem trace

Each stack entry remembers the minimum that existed beneath it

Input and goalBuild a stack that returns its current minimum in constant time.
Initialize an empty MinStackBefore any operation, the pair stack is empty.
emptytopempty
columnsvalue | minimum so farlayoutbottom to topoperationspush(5), push(2), push(4), get_min(), pop(), get_min(), top()actioninitialize
top
(0, 0)
columns
value | minimum so far
layout
bottom to top

Recognize it
Use this pattern when ordinary stack operations must also answer an aggregate such as the current minimum in constant time, including immediately after pops.
Keep true
For every stored pair (value, minimum), minimum equals the smallest value from the bottom through that pair; therefore the top pair summarizes the complete current stack.
Reuse it
Attach any reversible prefix summary needed later to each stack item; the same technique supports max stacks, depth summaries, and constant-time aggregate reads after rollback.
Before any operation, the pair stack is empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: After removing both 4 and 2, where does the restored minimum 5 come from without rescanning the stack?
Reference drawing

Problem trace

Each stack entry remembers the minimum that existed beneath it

Worked example: duplicate minima need duplicate historical statePushing 5,2,2 stores minima 5,2,2. Popping one 2 must leave minimum 2; recording only distinct minima would incorrectly restore 5.Each value owns its ownminimum-so-far snapshotBefore popvalue | min552222After onepopvalue | min5522The surviving top pair is still valuetwo / minimum two.
Execution trace
Input and goalBuild a stack that returns its current minimum in constant time.
Initialize an empty MinStackBefore any operation, the pair stack is empty.
emptytopempty
columnsvalue | minimum so farlayoutbottom to topoperationspush(5), push(2), push(4), get_min(), pop(), get_min(), top()actioninitialize
top
(0, 0)
columns
value | minimum so far
layout
bottom to top

Recognize it
Use this pattern when ordinary stack operations must also answer an aggregate such as the current minimum in constant time, including immediately after pops.
Keep true
For every stored pair (value, minimum), minimum equals the smallest value from the bottom through that pair; therefore the top pair summarizes the complete current stack.
Reuse it
Attach any reversible prefix summary needed later to each stack item; the same technique supports max stacks, depth summaries, and constant-time aggregate reads after rollback.
Before any operation, the pair stack is empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: After removing both 4 and 2, where does the restored minimum 5 come from without rescanning the stack?
Read it this way: Pushing 5,2,2 stores minima 5,2,2. Popping one 2 must leave minimum 2; recording only distinct minima would incorrectly restore 5. After popping one two, which surviving snapshot still establishes minimum two?
OperationStored pairs, bottom to topResult
push(5)(5, 5)None
push(2)(5, 5), (2, 2)None
push(4)(5, 5), (2, 2), (4, 2)None
get_min()Unchanged2
pop()(5, 5), (2, 2)None
get_min(); top()Unchanged2; 2

Each pair’s second field is the minimum from the bottom through that level. A push combines its value with the preceding saved minimum. A pop removes one pair, leaving every earlier summary unchanged. Duplicate minima retain separate levels: push(2), push(2), pop() must still report 2.

Code

class MinStack:
   def __init__(self) -> None:
      self.stack: list[tuple[int, int]] = []

   def push(self, value: int) -> None:
      minimum = min(value, self.stack[-1][1]) if self.stack else value
      self.stack.append((value, minimum))

   def pop(self) -> None:
      self.stack.pop()

   def top(self) -> int:
      return self.stack[-1][0]

   def get_min(self) -> int:
      return self.stack[-1][1]

Indexed reads are constant-time; Python list pushes and pops are amortized , not strict worst-case guarantees. Storage is pairs for entries, under ordinary integer-comparison costs.

Change 1: Save Minimum and Maximum

New task. Query both bounds after rollback.

Picture and change. Store (value, minimum, maximum) per level.

Code.

class MinMaxStack:
   def __init__(self):
      self.stack = []

   def push(self, value):
      minimum = min(value, self.stack[-1][1]) if self.stack else value
      maximum = max(value, self.stack[-1][2]) if self.stack else value
      self.stack.append((value, minimum, maximum))

   def pop(self):
      self.stack.pop()

   def limits(self):
      return list(self.stack[-1][1:])

def minmax_rollback(values):
   stack = MinMaxStack()
   for value in values:
      stack.push(value)
   before = stack.limits()
   stack.pop()
   return [before, stack.limits()]

Check. [5, 2, 1] gives [[1, 5], [2, 5]]. The wrapper requires at least two values.

Use when. Several constant-size prefix summaries are needed.

Change 2: Observe Every Restored Minimum

New task. Report minima during all pushes and pops.

Picture and change. Use the retained MinStack; never query after its final pop.

Code. Place after MinStack:

def minima_during_rollback(values):
   stack = MinStack()
   answer = []
   for value in values:
      stack.push(value)
      answer.append(stack.get_min())
   for remaining in range(len(values) - 1, -1, -1):
      stack.pop()
      if remaining:
         answer.append(stack.get_min())
   return answer

Check. [5, 2, 4] gives [5, 2, 2, 2, 5]; [2, 2] gives [2, 2, 2]; empty input gives [].

Use when. The caller needs an auditable sequence; its output needs additional storage.

Failure: Keeping Only One Minimum

When the minimum is popped, one scalar cannot recover the previous minimum without retained history or a rescan.

Transfer Check

Must the aggregate have an inverse?

Reasoned Answer

No. Earlier prefix answers remain stored at their own levels. Pop restores state instead of undoing min algebraically.

Restoration Is Not an Inverse

Both min(5, 1) and min(9, 1) produce 1. The result and last value alone cannot identify the earlier answer. The stack avoids that information loss by keeping each earlier summary alongside its corresponding prefix.

The min/max extension preserves amortized constant operation costs and linear stored state. Its limits operation returns [minimum, maximum] and requires a nonempty stack, as does pop. The trace wrapper needs two initial entries because it queries before and after one removal.

This structure supports last-in-first-out rollback, not arbitrary middle deletion. Removing an interior entry could invalidate every summary above it and requires a different data structure or recomputation. For comparison, two-sided scans combine saved left contributions with a separately accumulated right contribution.