1706. Peak Stack

Medium3.5 points estimatedStackDesignOrdered SetHeap

A plate dispenser is a last-in, first-out stack, but the chef also wants to grab the heaviest plate. Design a class PeakStack with a constructor that takes no arguments and these methods: push(x) places x on top of the stack and returns nothing; pop() removes and returns the top element; top() returns the top element without removing it; peekMax() returns the largest value in the stack without removing it; popMax() removes and returns the largest value.

When the maximum occurs several times, popMax removes only the occurrence nearest the top of the stack. Every method returns -1 when the stack is empty (values are never negative, so this is unambiguous). Each call should run in O(log n) time: give every pushed entry an insertion stamp and keep an ordered set or a max-heap keyed by (value, stamp), deleting lazily or eagerly as you prefer. Space is O(n).

Example 1

Input:
operations = ["PeakStack","push","push","push","top","popMax","top","peekMax","pop","peekMax"]arguments = [[],[5],[1],[5],[],[],[],[],[],[]]
Output:
[null,null,null,null,5,5,1,5,1,5]
Explanation:

After pushing 5, 1, 5 the top is 5; popMax removes the upper 5, leaving 5, 1 so the top is 1 and the maximum is still 5; pop returns 1 and the maximum is 5.

Example 2

Input:
operations = ["PeakStack","top","peekMax","pop","popMax","push","top"]arguments = [[],[],[],[],[],[4],[]]
Output:
[null,-1,-1,-1,-1,null,4]
Explanation:

Every query on an empty stack returns -1; after push(4) the top is 4.

Example 3

Input:
operations = ["PeakStack","push","push","push","popMax","top","popMax","popMax","popMax"]arguments = [[],[3],[9],[2],[],[],[],[],[]]
Output:
[null,null,null,null,9,2,3,2,-1]
Explanation:

After pushing 3, 9, 2, popMax returns 9, the top is 2, and further popMax calls return 3, then 2, then -1 on the empty stack.

Constraints

0 ≤ x ≤ 109

At most 1000 calls in total

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(log n) per call
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.