Skip to content
BytePatterns

Constant Time Min Stack

EasyStacks & Queues#stack#auxiliary-stack~20m

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

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