An undo history keeps its entries on a stack, but users can also jump straight to the most important entry and remove it. Each entry has a numeric priority. You need a stack that, besides the usual operations, can report and remove its largest value.
Implement a class MaxStack:
push(value) puts value on top and returns the new size.
pop() removes the top value and returns it.
top() returns the top value without removing it.
peekMax() returns the largest value without removing it.
popMax() removes the largest value and returns it. If the largest value appears several times, it removes the one closest to the top (the most recently pushed). The other values keep their order.
size is a getter with the number of values.
Rules:
pop, top, peekMax and popMax return undefined on an empty stack.
push throws a TypeError unless value is a finite number.
Stacks can hold 100,000 values and see 100,000 popMax calls. Every operation must be O(log n) amortised: scanning the stack, or popping values into a buffer until the maximum appears and pushing them back, is too slow when the maximum sits at the bottom.
const stack = new MaxStack();stack.push(5);stack.push(1);stack.push(5);stack.top(); // 5stack.popMax(); // 5: the upper of the two 5sstack.top(); // 1stack.peekMax(); // 5stack.pop(); // 1stack.top(); // 5stack.size; // 1
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.