Max Stack - Problem
Design a max stack data structure that combines the functionality of a traditional stack with efficient maximum element retrieval. Think of it as a smart stack that always knows its maximum element!
Your MaxStack class must support these operations:
push(x)- Add element x to the top of the stackpop()- Remove and return the top elementtop()- Get the top element without removing itpeekMax()- Find the maximum element without removing itpopMax()- Remove and return the maximum element (if multiple exist, remove the topmost one)
Performance Requirements: top() must run in O(1) time, while all other operations should run in O(log n) time.
Example: If your stack contains [5, 1, 5] (bottom to top), calling popMax() should remove the top 5 (not the bottom one) and return it.
Input & Output
example_1.py โ Basic Operations
$
Input:
["MaxStack","push","push","push","top","popMax","top","peekMax","pop","top"]
[[],[5],[1],[5],[],[],[],[],[],[]]
โบ
Output:
[null,null,null,null,5,5,1,5,1,5]
๐ก Note:
MaxStack stk = new MaxStack(); stk.push(5); stk.push(1); stk.push(5); stk.top(); // return 5; stk.popMax(); // return 5; stk.top(); // return 1; stk.peekMax(); // return 5; stk.pop(); // return 1; stk.top(); // return 5
example_2.py โ Duplicate Maximums
$
Input:
["MaxStack","push","push","push","popMax","popMax","popMax"]
[[],[3],[3],[3],[],[],[]]
โบ
Output:
[null,null,null,null,3,3,3]
๐ก Note:
When multiple maximum elements exist, popMax() removes the topmost one first. All three 3's are removed in LIFO order.
example_3.py โ Mixed Operations
$
Input:
["MaxStack","push","push","peekMax","push","peekMax","popMax","top"]
[[],[1],[2],[],[3],[],[],[]]
โบ
Output:
[null,null,null,2,null,3,3,2]
๐ก Note:
Stack evolution: [1] โ [1,2] โ peek 2 โ [1,2,3] โ peek 3 โ popMax removes 3 โ [1,2] โ top is 2
Constraints
- -107 โค x โค 107
- At most 104 calls will be made to push, pop, top, peekMax, and popMax
- There will be at least one element in the stack when pop, top, peekMax, or popMax is called
Visualization
Tap to expand
Understanding the Visualization
1
Order Arrives
New order goes on top of the spike AND gets logged in the priority ledger
2
Regular Service
Normal orders are taken from the top of the spike (LIFO)
3
Priority Service
When a VIP order needs to be served, quickly locate it using the ledger and remove it from the spike
4
Efficient Tracking
The dual system ensures both stack operations and priority lookups are fast
Key Takeaway
๐ฏ Key Insight: By maintaining elements in both a doubly-linked list (for stack order) and a TreeMap (for value priority), we achieve O(1) top operations and O(log n) max operations - the perfect balance of efficiency!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code