Dinner Plate Stacks
Design DinnerPlates with a fixed capacity per stack. push(val) places the value on the leftmost stack that is not full (creating a new rightmost stack if all are full). pop() removes and returns the value from the rightmost non-empty stack, or -1 if all are empty. popAtStack(index) removes and returns the top of the stack at the given index, or -1 if that stack is empty or does not exist.
Open official problem prompt ↗Route each push to the leftmost stack with free space and each pop to the rightmost non-empty stack, even as middle stacks empty and refill.
A cafeteria counter of plate dispensers, each holding a fixed number of plates. Diners take from the far-right dispenser, but a busboy always refills the leftmost one that has room; a directory of which dispensers have space keeps refilling fast.
- Input
- DinnerPlates(2); push(1); push(2); push(3); push(4); push(5); popAtStack(0); push(20); push(21); popAtStack(0); popAtStack(2); pop(); pop(); pop(); pop(); pop()
- Output
- [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]
- Why
- Capacity 2 gives stacks [1,2],[3,4],[5]; popAtStack(0) returns 2 freeing a left slot, so push(20) refills stack 0 and push(21) fills stack 2; the popAtStacks return 20 and 21; then pops peel from the right: 5,4,3,1, and finally -1 when empty.
1 <= capacity <= 2 * 10^41 <= val <= 2 * 10^40 <= index < number of stacks that have ever existedAt most 2 * 10^5 calls to push, pop, and popAtStack