Skip to content

Constant Time Min Stack

Easy#stack#auxiliary-stack~20 min

The mission

Problem

Design a stack that supports pushing a value, popping the top value, reading the top value, and reporting the smallest value currently stored. Every one of those operations must run in constant time, so scanning the contents to find the minimum is not acceptable. You may assume the minimum is only requested while the stack is non-empty.

Examples

Operations: push 5, push 2, push 7
minimum -> 2, top -> 7
Operations: pop, pop        (starting from the stack above)
minimum -> 5, top -> 5
Why:       popping 2 must restore the earlier minimum
Operations: push 3, push 3, pop
minimum -> 3
Why:       edge case, duplicate minimums must survive one pop

Hints

0 / 3

Target time
O(1)
Target space
O(n)

Constraints

  • every operation runs in O(1) time
  • minimum is only requested on a non-empty stack

Stuck on the idea rather than the code? Min Stack covers it.

Python 3Ctrl+Enter runs