Baseline Stack and Queues · Learning O(1) push, O(n) pop · O(n)
A cafeteria passes trays along a single-file line, but the chef wants the tray added most recently to be the one served next — the opposite of how the line naturally works. The workaround: whenever a serving is requested, the kitchen cycles every tray except the newest around the line once, so the newest tray arrives at the serving end. Implement this controller so push stays cheap and each pop serves the freshest tray.
Input: A list of operations, each either ["push", value] to insert or ["pop"] to remove.
Output: Return the list of values produced by every pop operation, in order; a pop on an empty structure yields -1.
1 <= number of operations <= 10^5-10^9 <= pushed values <= 10^9Only a single FIFO queue may be used internallyInput: {"operations":[["push",1],["push",2],["pop"],["push",3],["pop"],["pop"]]}
Output: [2,3,1]
Pop rotates 1 to the back and serves 2; afterwards 3 then 1 leave in LIFO order.
Input: {"operations":[["push",5],["pop"],["pop"]]}
Output: [5,-1]
The lone element is served first; the second pop hits an empty queue.