Max Stack
Hard
Topics
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
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
- Keep the values in a stack (a list) for ordering.
- top and pop act on the end; peekMax scans (or a balanced structure tracks) the maximum.
- 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 bestimport java.util.*;
class MaxStack {
private final Deque<Integer> stack = new ArrayDeque<>();
private final Deque<Integer> maxes = new ArrayDeque<>();
public MaxStack() {
}
public void push(int x) {
maxes.push(maxes.isEmpty() ? x : Math.max(maxes.peek(), x));
stack.push(x);
}
public int top() {
return stack.peek();
}
public int pop() {
maxes.pop();
return stack.pop();
}
public int peekMax() {
return maxes.peek();
}
public int popMax() {
int best = maxes.peek();
Deque<Integer> buffer = new ArrayDeque<>();
while (stack.peek() != best) buffer.push(pop());
pop();
while (!buffer.isEmpty()) push(buffer.pop());
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class MaxStack {
public: MaxStack() {
}
void push(int x) {
stack_.push_back(x);
maxes_.push_back(maxes_.empty() ? x : max(maxes_.back(), x));
}
int top() {
return stack_.back();
}
int pop() {
maxes_.pop_back();
int out = stack_.back();
stack_.pop_back();
return out;
}
int peekMax() {
return maxes_.back();
}
int popMax() {
int best = maxes_.back();
vector<int> buffer;
while (stack_.back() != best) buffer.push_back(pop());
pop();
while (!buffer.empty()) {
push(buffer.back());
buffer.pop_back();
}
return best;
}
private: vector<int> stack_, maxes_;
};class MaxStack {
constructor() {
this.stack = [];
this.maxes = [];
}
push(x) {
this.stack.push(x);
this.maxes.push(this.maxes.length ? Math.max(this.maxes[this.maxes.length - 1], x) : x);
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
this.maxes.pop();
return this.stack.pop();
}
peekMax() {
return this.maxes[this.maxes.length - 1];
}
popMax() {
const best = this.maxes[this.maxes.length - 1];
const buffer = [];
while (this.stack[this.stack.length - 1] !== best) buffer.push(this.pop());
this.pop();
while (buffer.length) this.push(buffer.pop());
return best;
}
}