Min Stack

Medium Design

MinStack() is a stack of whole numbers, empty to begin with, that can also tell you the smallest number it holds.

push(val) puts val on top of the stack. pop() takes the number on top off the stack. top() returns the number on top and leaves it where it is.

getMin() returns the smallest number in the stack and leaves the stack as it is. A number pushed more than once is in the stack once for each push, so popping one copy of the smallest leaves the others, and the smallest is still that number.

Example 1

Calls:
MinStack()
push(4)
push(7)
push(2)
getMin() → 2
top() → 2
pop()
getMin() → 4
top() → 7

2 is the smallest while it is in the stack. Once it is popped, the smallest of 4 and 7 is 4 again, and 7 is on top.

Example 2

Calls:
MinStack()
push(5)
push(3)
push(3)
pop()
getMin() → 3
pop()
getMin() → 5

Example 3

Calls:
MinStack()
push(0)
push(-6)
push(9)
getMin() → -6
pop()
pop()
getMin() → 0
top() → 0

Constraints

  • -10⁹ ≤ val ≤ 10⁹
  • pop, top and getMin are called only when the stack holds at least one number
  • at most 3 × 10⁵ calls in all to push, pop, top and getMin

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Design

All Design problems