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

returnsMaxStack()push(5)push(1)push(5)top()5popMax()5top()1peekMax()5pop()1top()5
A second stack of running maxima handles peekMax, as in min-stack. popMax is the hard one, because it removes from the middle: the usual fix is to pop into a buffer, discard the maximum, and push the buffer back — or to pair a tree map with a doubly linked list for true log-time.
Calls run top to bottom; the arrow shows what each one returns.
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.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A normal stack handles push/top/pop. The extra requirement is fast max lookup and removal of the top-most maximum, which needs the stack order preserved even after removing an element from the middle.

Approach

  1. Keep the values in a stack (a list) for ordering.
  2. top and pop act on the end; peekMax scans (or a balanced structure tracks) the maximum.
  3. popMax finds the last occurrence of the maximum and removes it, preserving the order of the rest.

Dry Run

maxes[i] is the running maximum of everything at or below depth i.

push 5     stack=[5]        maxes=[5]
push 1     stack=[5, 1]     maxes=[5, 5]      1 did not beat 5
push 5     stack=[5, 1, 5]  maxes=[5, 5, 5]
top        -> 5             reads stack[-1]
popMax     best = maxes[-1] = 5
           stack[-1] is already 5, so nothing is buffered
           pop once         stack=[5, 1]      maxes=[5, 5]
           -> 5
top        -> 1
peekMax    -> 5             reads maxes[-1], O(1)
pop        -> 1             stack=[5]         maxes=[5]
top        -> 5

answer null null null null 5 5 1 5 1 5

The two stacks move in lockstep, which is what makes peekMax O(1) rather than a
scan. popMax is the expensive one and the only one that breaks that lockstep
temporarily: it pops into a buffer until the maximum is on top, removes it, then
pushes the buffer back -- so the maxes array is rebuilt correctly on the way
back rather than patched. That is why the buffered values go back through
`push` and not straight onto `stack`.

Complexity

  • Time — O(n) for max ops: peekMax/popMax scan the stack; push/top/pop are O(1). A balanced BST plus doubly-linked list makes max ops O(log n).
  • Space — O(n): the stack holds all elements.

Common Pitfalls

  • popMax must remove the top-most maximum (scan from the end), not the first occurrence.

Full Solution — all languages

class MaxStack:
    def __init__(self):
        self.stack = []
        # running maximum of everything at or below each depth
        self.maxes = []

    def push(self, x):
        self.stack.append(x)
        self.maxes.append(x if not self.maxes else max(self.maxes[-1], x))

    def top(self):
        return self.stack[-1]

    def pop(self):
        self.maxes.pop()
        return self.stack.pop()

    def peekMax(self):
        return self.maxes[-1]

    def popMax(self):
        best = self.maxes[-1]
        buffer = []
        while self.stack[-1] != best:
            buffer.append(self.pop())
        self.pop()
        while buffer:
            self.push(buffer.pop())
        return best
SensAI
Beta
Tap the mic to stop voice mode