Min Stack - Problem
Imagine you're building a smart stack that not only stores elements but also instantly knows its minimum value at all times! This is more challenging than it sounds because stacks only allow access to the top element.
Your task is to design a MinStack class that supports these operations:
push(val)- Add an element to the toppop()- Remove the top elementtop()- Get the top elementgetMin()- Get the minimum element
The catch? All operations must run in O(1) constant time! No scanning through the entire stack allowed.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2 Input & Output
example_1.py — Basic Operations
$
Input:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
›
Output:
[null,null,null,null,-3,null,0,-2]
💡 Note:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3; minStack.pop(); minStack.top(); // return 0; minStack.getMin(); // return -2
example_2.py — Duplicate Minimums
$
Input:
["MinStack","push","push","push","getMin","pop","getMin"]
[[],[1],[1],[1],[],[],[]]
›
Output:
[null,null,null,null,1,null,1]
💡 Note:
When all elements are the same, the minimum remains constant. After popping one element, the minimum is still 1.
example_3.py — Ascending Order
$
Input:
["MinStack","push","push","push","getMin","pop","getMin","pop","getMin"]
[[],[3],[2],[1],[],[],[],[],[]]
›
Output:
[null,null,null,null,1,null,2,null,3]
💡 Note:
Elements pushed in descending order. Each pop operation reveals the next minimum in the remaining stack.
Constraints
- -231 <= val <= 231 - 1
- Methods pop, top and getMin operations will always be called on non-empty stacks
- At most 3 × 104 calls will be made to push, pop, top, and getMin
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code