Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.

Implement the MaxStack class:

  • MaxStack() Initializes the stack object.
  • void push(int x) Pushes element x onto the stack.
  • int pop() Removes the element on top of the stack and returns it.
  • int top() Gets the element on the top of the stack without removing it.
  • int peekMax() Retrieves the maximum element in the stack without removing it.
  • int popMax() Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one.

You must come up with a solution that supports O(1) for each top call and O(log n) for each other call.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["MaxStack","push","push","top","popMax","top"], values = [[],[5],[1],[],[],[]]
Output: [null,null,null,1,5,1]
💡 Note: MaxStack() creates empty stack. push(5) adds 5. push(1) adds 1 on top. top() returns 1 (top element). popMax() removes and returns 5 (maximum). top() returns 1 (now the only element).
Example 2 — Multiple Max Elements
$ Input: operations = ["MaxStack","push","push","push","peekMax","popMax","top"], values = [[],[5],[1],[5],[],[],[]]
Output: [null,null,null,null,5,5,1]
💡 Note: After pushing 5,1,5: stack is [5,1,5]. peekMax() returns 5. popMax() removes the top-most 5, leaving [5,1]. top() returns 1.
Example 3 — Pop vs PopMax
$ Input: operations = ["MaxStack","push","push","push","pop","popMax"], values = [[],[3],[2],[1],[],[]]
Output: [null,null,null,null,1,3]
💡 Note: Stack becomes [3,2,1]. pop() removes top element 1, leaving [3,2]. popMax() removes maximum 3, leaving [2].

Constraints

  • -107 ≤ x ≤ 107
  • At most 105 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
Max Stack: Stack Operations + Max Element TrackingOperationspush(5), push(1)top() → 1popMax() → 5top() → 1Stack State15topmaxRequirementstop(): O(1)push(): O(log n)pop(): O(log n)peekMax/popMax: O(log n)Challenge: Efficiently support both stack and max operationsSolution: Doubly-Linked List + TreeMap/Ordered Set
Understanding the Visualization
1
Input
Sequence of operations: push, pop, top, peekMax, popMax
2
Process
Maintain stack order while tracking maximum element
3
Output
Results of each operation with O(1) top and O(log n) others
Key Takeaway
🎯 Key Insight: Combine doubly-linked list for O(1) stack operations with ordered data structure for O(log n) max operations
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
89.0K Views
Medium Frequency
~35 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen