Skip to main content

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class.

Problems46 / 152
Sign in

Min Stack

MEDIUMStackDesign

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class.

Example 1

Input:  operations = ["MinStack","push","push","push","getMin","pop","top","getMin"], values = [[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]

Example 2

Input:  operations = ["MinStack","push","push","getMin","pop","getMin"], values = [[],[1],[2],[],[],[]]
Output: [null,null,null,1,null,1]
Show hint

Use two stacks: one for values, one for minimums. Or store pairs (value, min) in single stack. Or use a variable to track min and handle updates.

Draft saves automatically

Loading editor...

Submit also runs hidden tests
operations =
["MinStack","push","push","push","getMin","pop","top","getMin"]
values =
[[],[-2],[0],[-3],[],[],[],[]]
Expected
[null,null,null,null,-3,null,0,-2]
Run with your own input (JSON)