Max Stack Problem
Description
LeetCode Problem 716.
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the MaxStack class:
MaxStack()Initializes the stack object.void push(int x)Pushes elementxonto the stack.int pop()Removes the element on top of the stack and returns it.int top()Gets the element on the top of the stack without removing it.int peekMax()Retrieves the maximum element in the stack without removing it.int popMax()Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one.
You must come up with a solution that supports O(1) for each top call and O(logn) for each other call.
Example 1:
Input
["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
[[], [5], [1], [5], [], [], [], [], [], []]
Output
[null, null, null, null, 5, 5, 1, 5, 1, 5]
Explanation
MaxStack stk = new MaxStack();
stk.push(5); // [5] the top of the stack and the maximum number is 5.
stk.push(1); // [5, 1] the top of the stack is 1, but the maximum is 5.
stk.push(5); // [5, 1, 5] the top of the stack is 5, which is also the maximum, because it is the top most one.
stk.top(); // return 5, [5, 1, 5] the stack did not change.
stk.popMax(); // return 5, [5, 1] the stack is changed now, and the top is different from the max.
stk.top(); // return 1, [5, 1] the stack did not change.
stk.peekMax(); // return 5, [5, 1] the stack did not change.
stk.pop(); // return 1, [5] the top of the stack and the max element is now 5.
stk.top(); // return 5, [5] the stack did not change.
Constraints:
-10^7 <= x <= 10^7- At most
10^5calls will be made topush,pop,top,peekMax, andpopMax. - There will be at least one element in the stack when
pop,top,peekMax, orpopMaxis called.
Solution
Approach: Stack and Max-Heap with Lazy Deletion
A stack gives top and pop, and a max-heap gives peekMax and popMax. The trouble is that removing an element through one structure leaves it in the other, and neither can delete from the middle cheaply.
Instead of deleting right away, we delete lazily. Give every pushed element a unique, increasing id and store (x, id) in both the stack and the heap. Keep a removed[id] flag:
push(x): add(x, id)to both structures.pop(): first discard stack entries whose element is already removed, then pop the top and mark it removed. Its copy in the heap stays until it reaches the top of the heap.popMax(): the same on the heap side, then mark the element removed so the stack skips it later.top()andpeekMax(): discard removed entries from the top of their structure, then look.
The heap orders by value, and among equal values by larger id first. That makes popMax remove the top-most of several equal maxima, as required. In the example, push 5, 1, 5 then popMax removes the second 5, leaving [5, 1].
Each element is discarded at most once from each structure, so the cleanup is paid for by the push that created the entry.
Complexity: O(log n) amortized time for push, pop, peekMax and popMax, and O(1) amortized for top. O(n) extra space, where n is the number of pushes.
import heapq
class MaxStack:
def __init__(self):
self.stack = [] # (x, id) in push order
self.heap = [] # (-x, -id): largest value first, and the newest among equal values
self.removed = [] # removed[id]: already taken out through the other structure
def push(self, x: int) -> None:
i = len(self.removed)
self.removed.append(False)
self.stack.append((x, i))
heapq.heappush(self.heap, (-x, -i))
def pop(self) -> int:
self._clean_stack()
x, i = self.stack.pop()
self.removed[i] = True
return x
def top(self) -> int:
self._clean_stack()
return self.stack[-1][0]
def peekMax(self) -> int:
self._clean_heap()
return -self.heap[0][0]
def popMax(self) -> int:
self._clean_heap()
x, i = heapq.heappop(self.heap)
self.removed[-i] = True
return -x
# Drop entries whose element was already removed through the other structure.
def _clean_stack(self):
while self.removed[self.stack[-1][1]]:
self.stack.pop()
def _clean_heap(self):
while self.removed[-self.heap[0][1]]:
heapq.heappop(self.heap)
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()