AlgoInsight

DSA problem

Max Stack

HardData Structure DesignPattern: Data Structure Designtop600AmazonGoogleMicrosoftLinkedInBloomberg

Design a max stack data structure that supports the stack operations push, pop, top, plus two extras: peekMax returns the maximum element in the stack, and popMax retrieves and removes the maximum element. If there is more than one maximum, only remove the top-most one.

The hard part is popMax. A normal stack with an auxiliary max-stack handles peekMax in O(1), but popMax must remove an arbitrary element from the middle of the main stack and still preserve the original push order of every other element. That rules out simple array-of-pairs solutions for O(log n) targets.

The optimal solution uses two ordered sets (TreeSets) of (value, id) pairs, where id is a monotonically increasing counter assigned on each push. The first set, ordered by id, mirrors the stack order — its largest entry is the current top. The second set, ordered by (value, id), lets us find the maximum (largest value, breaking ties by largest id so we get the top-most). Both sets store the same pairs, so removing one entry costs O(log n) in each set.

push inserts (val, ++id) into both sets. pop removes the last entry of the main set and the matching entry from the max set. top peeks the last entry of the main set. peekMax peeks the last entry of the max set. popMax removes the last entry of the max set (largest value, top-most among ties) and the matching entry from the main set. Every operation runs in O(log n).

Examples

Example 1
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]
Explanation: After pushes the stack is bottom->top: [5,1,5]. top=5. popMax removes the top 5 -> [5,1], returns 5. top=1. peekMax=5. pop=1. top=5.
Example 2
Input: ["MaxStack","push","push","peekMax","popMax","top"] [[],[2],[7],[],[],[]]
Output: [null,null,null,7,7,2]
Explanation: Push 2,7 -> stack [2,7]. peekMax=7. popMax removes 7 -> [2], returns 7. top=2.
Example 3
Input: ["MaxStack","push","push","push","popMax","popMax","popMax"] [[],[3],[3],[3],[],[],[]]
Output: [null,null,null,null,3,3,3]
Explanation: Three equal maxima. popMax always removes the top-most one, so the stack shrinks 3,3,3 -> 3,3 -> 3 -> [].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackdesignordered-setdata-structure

Browse all DSA problems