Skip to content

visual walkthrough

Min Stack

MediumMin/Aux StackReported at: AmazonMicrosoftMeta+5

Keeping auxiliary state per element is a reusable design trick.

Solve on LeetCode

The idea

The minimum of a stack changes only when you push a smaller value or pop the current minimum. So store, next to every element, the minimum of everything beneath and including it.

Then getMin is just a peek at the matching top entry, and popping automatically restores the previous minimum.

Complexity

approachtimespace
One stack, scan for minO(n) getMinO(n)
Parallel min stackO(1) allO(n)

More walkthroughs