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,4,3,2,null,5]
💡 Note:
Initialize with capacity 2, push 1,2,3,4 (creates stacks [[1,2],[3,4]]), pop returns 4,3,2, push 5 goes to first available spot in stack 0, final pop returns 5
Example 2 — PopAtStack Usage
$
Input:
Operations: ["DinnerPlates","push","push","popAtStack","push","pop"], Values: [[1],[1],[2],[0],[3],[]]
›
Output:
[null,null,null,1,null,2]
💡 Note:
Capacity 1, push 1,2 creates [[1],[2]], popAtStack(0) removes 1, push 3 goes to stack 0, pop returns 2 from rightmost stack
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code