Dinner Plate Stacks Problem
Description
LeetCode Problem 1172.
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.
Implement the DinnerPlates class:
DinnerPlates(int capacity)Initializes the object with the maximum capacity of the stackscapacity.void push(int val)Pushes the given integervalinto the leftmost stack with a size less thancapacity.int pop()Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns-1if all the stacks are empty.int popAtStack(int index)Returns the value at the top of the stack with the given indexindexand removes it from that stack or returns-1if the stack with that given index is empty.
Example 1:
Input
["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"]
[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]
Output
[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]
Explanation:
DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5); // The stacks are now: 2 4
1 3 5
﹈ ﹈ ﹈
D.popAtStack(0); // Returns 2. The stacks are now: 4
1 3 5
﹈ ﹈ ﹈
D.push(20); // The stacks are now: 20 4
1 3 5
﹈ ﹈ ﹈
D.push(21); // The stacks are now: 20 4 21
1 3 5
﹈ ﹈ ﹈
D.popAtStack(0); // Returns 20. The stacks are now: 4 21
1 3 5
﹈ ﹈ ﹈
D.popAtStack(2); // Returns 21. The stacks are now: 4
1 3 5
﹈ ﹈ ﹈
D.pop() // Returns 5. The stacks are now: 4
1 3
﹈ ﹈
D.pop() // Returns 4. The stacks are now: 1 3
﹈ ﹈
D.pop() // Returns 3. The stacks are now: 1
﹈
D.pop() // Returns 1. There are no stacks.
D.pop() // Returns -1. There are still no stacks.
Constraints:
1 <= capacity <= 2 * 10^41 <= val <= 2 * 10^40 <= index <= 10^5- At most
2 * 10^5calls will be made topush,pop, andpopAtStack.
Solution
Approach: Array of Stacks + Min-Heap of Open Slots
Keep the stacks in an array, left to right. pop is easy if we never leave an empty stack at the right end: then the rightmost non-empty stack is simply the last one. So after every removal we drop empty stacks from the end of the array.
The hard part is push, which needs the leftmost stack that still has room. Scanning from the left is too slow with 2 * 105 calls, so we keep a min-heap of indices of stacks that may have room:
popAtStack(index)takes a plate off stackindex, so that stack now has room: pushindexonto the heap.- When every stack is full (the heap is empty),
pushstarts a new stack at the right end and puts its index on the heap. pushputs the plate on the stack at the top of the heap.
The heap is allowed to hold stale entries: an index whose stack has filled up again, or an index past the end of the array because trailing empty stacks were dropped. Instead of deleting those when they go stale, push pops them off the top of the heap until the top is a real stack with room. Every stack with room is always in the heap, so the first valid top is the leftmost one.
pop() is just popAtStack(last index), which returns -1 when there are no stacks at all.
Complexity: O(log n) amortized time per call, where n is the number of calls: each index pushed onto the heap is popped at most once. O(n) space for the plates and the heap.
import heapq
class DinnerPlates:
def __init__(self, capacity: int):
self.capacity = capacity
self.stacks = []
# Min-heap of indices of stacks that may have room. Entries can be stale
# (the stack filled up or was removed); push() skips those.
self.open = []
def push(self, val: int) -> None:
while self.open and (self.open[0] >= len(self.stacks)
or len(self.stacks[self.open[0]]) == self.capacity):
heapq.heappop(self.open)
if not self.open: # every stack is full: start a new one on the right
heapq.heappush(self.open, len(self.stacks))
self.stacks.append([])
self.stacks[self.open[0]].append(val)
def pop(self) -> int:
return self.popAtStack(len(self.stacks) - 1)
def popAtStack(self, index: int) -> int:
if index < 0 or index >= len(self.stacks) or not self.stacks[index]:
return -1
val = self.stacks[index].pop()
heapq.heappush(self.open, index) # this stack has room now
# Drop empty stacks at the right end, so the last stack is never empty.
while self.stacks and not self.stacks[-1]:
self.stacks.pop()
return val