Dinner Plate Stacks - Problem
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0. Each stack has the same maximum capacity.
Implement the DinnerPlates class:
DinnerPlates(int capacity)- Initializes the object with the maximum capacity of the stacks.void push(int val)- Pushes the given integervalinto the leftmost stack with a size less than capacity.int pop()- Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns-1if all stacks are empty.int popAtStack(int index)- Returns the value at the top of the stack with the givenindexand removes it from that stack or returns-1if the stack is empty.
Input & Output
Example 1 — Basic Operations
$
Input:
Operations: ["DinnerPlates","push","push","push","push","pop","pop","pop","push","pop"], Values: [[2],[1],[2],[3],[4],[],[],[],[5],[]]
›
Output:
[null,null,null,null,null,2,1,-1,null,2]
💡 Note:
Initialize with capacity 2, push 1,2,3,4 (creates stacks [[1,2],[3,4]]), pop returns 4,2,1, push 5 goes to first available spot, final pop returns 2
Example 2 — PopAtStack Usage
$
Input:
Operations: ["DinnerPlates","push","push","popAtStack","push","pop"], Values: [[1],[1],[2],[0],[3],[]]
›
Output:
[null,null,null,1,null,3]
💡 Note:
Capacity 1, push 1,2 creates [[1],[2]], popAtStack(0) removes 1, push 3 goes to stack 0, pop returns 3
Example 3 — Empty Stack Handling
$
Input:
Operations: ["DinnerPlates","pop","push","pop","pop"], Values: [[2],[],[1],[],[]]
›
Output:
[null,-1,null,1,-1]
💡 Note:
Pop from empty returns -1, push 1, pop returns 1, pop from empty again returns -1
Constraints
- 1 ≤ capacity ≤ 2 × 104
- 1 ≤ val ≤ 2 × 104
- 0 ≤ index ≤ 105
- At most 2 × 105 calls to push, pop, and popAtStack
Visualization
Tap to expand
Understanding the Visualization
1
Input
Operations: push(1), push(2), push(3), push(4) with capacity=2
2
Process
Creates stacks: [[1,2], [3,4]] filling left to right
3
Output
Pop operations return from rightmost: 4, 2, 1
Key Takeaway
🎯 Key Insight: Use priority queues to efficiently track available stacks and rightmost positions for optimal performance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code