Limited time: AI code review, hints, mock interviews, whiteboard analysis, and all Pro features are unlocked. Enroll

Max Stack

Hard

Topics
StackDesignSorted Set

Design a stack that supports finding and removing the maximum element. Implement MaxStack() and: push(x), top() (returns the top element), pop() (removes and returns the top element), peekMax() (returns the maximum element), and popMax() (removes and returns the maximum element; if there are ties, remove the one closest to the top).

Example 1

Input:  operations = ["MaxStack","push","push","push","top","popMax","top","peekMax","pop","top"], values = [[],[5],[1],[5],[],[],[],[],[],[]]
Output: [null,null,null,null,5,5,1,5,1,5]

Constraints

  • -10^7 <= x <= 10^7
  • At most 10^4 calls.
  • top, pop, peekMax, popMax are only called on a non-empty stack.
Run ⌘' · Submit ⌘⏎
SensAI SensAI
Beta
Listening...
Tap mic to stop voice mode

Unlock AI Features

One click to activate - no payment, no credit card. Just sign in and you're in.

AI code review and hints
SensAI chat assistant
AI mock interviews
Whiteboard analysis
100% free during early access