CodeArchon

mediumStackAmazonBloomberg

Minimum-Aware Stack

Design a stack that supports push, pop, top, and getMin — each in O(1).

Implement a stack with: `push(x)`, `pop()`, `top()`, `getMin()`, every call O(1).

Choose approach

top
1/8
Narrationstep 1 of 8

Paired stacks: data holds pushed values, mins holds a running minimum. Push copies the new min; pop discards both tops.

1class MinStack:
2 def __init__(self):
3 self.data: list[int] = []
4 self.mins: list[int] = []
5 def push(self, x: int) -> None:
6 self.data.append(x)
7 self.mins.append(x if not self.mins else min(x, self.mins[-1]))
8 def pop(self) -> None:
9 self.data.pop()
10 self.mins.pop()
11 def top(self) -> int:
12 return self.data[-1]
13 def get_min(self) -> int:
14 return self.mins[-1]
Variables
ops=7

How to think about it

  1. A regular stack can't produce the min in O(1) without extra state.
  2. Store the running minimum per level in a parallel stack.
  3. Pushing x pushes min(x, old-top-min).
  4. Pop both stacks together.
  5. Top and getMin are just reads of each stack's top.

Edge cases to catch in interview

  • pop/top/min on empty stack — treat as undefined behaviour (problem guarantees valid calls).
  • Duplicates — mins stack stores them separately (correct).

Examples

Example 1-3, (pop), 0, -2
{"ops":[["push",-2],["push",0],["push",-3],["min"],["pop"],["top"],["min"]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed