Imagine you're managing a cafeteria where plates are organized in stacks. You have an infinite number of stacks arranged in a row, numbered from 0 (leftmost) onwards. Each stack has the same maximum capacity.
Your task is to implement a DinnerPlates class that efficiently manages these stacks:
- Push operation: Always add new plates to the leftmost stack that has space
- Pop operation: Always remove plates from the rightmost non-empty stack
- Pop at specific stack: Remove a plate from any specific stack by its index
The challenge is to handle these operations efficiently while maintaining the correct ordering and dealing with gaps that form when plates are removed from middle stacks.
Example: With capacity=2, after pushing [1,2,3,4,5] you get: Stack0=[1,2], Stack1=[3,4], Stack2=[5]. If you pop from Stack1, it becomes Stack0=[1,2], Stack1=[3], Stack2=[5], and the next push should fill Stack1 again, not create Stack3.
Input & Output
Constraints
- 1 โค capacity โค 2 ร 104
- 1 โค val โค 2 ร 104
- 0 โค index โค 105
-
At most 2 ร 105 calls will be made to
push,pop, andpopAtStack - Time limit: All operations should be efficient for large inputs