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
Understanding the Visualization
1
Smart Labeling
Each plate gets a smart label showing the most valuable plate up to that point
2
Adding Plates
When adding a new plate, compare its value with the current most valuable and update the label
3
Instant Access
The waiter can instantly see the most valuable plate by reading the top label
4
Removing Plates
When plates are removed, the labels automatically reveal the next most valuable plate
Key Takeaway
๐ฏ Key Insight: By maintaining minimum information at each stack level, we eliminate the need to search through all elements, achieving O(1) performance for all operations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code