Easy · Amortised Two Stacks
Understand → Visualise → Practice.
Process valid push, pop and peek operations on a FIFO queue implemented using two LIFO stacks; return pop and peek results.
Push to an 'in' stack. To pop or peek, take from an 'out' stack; if it's empty, move everything from 'in' to 'out', which reverses it into queue order.
Append to the incoming stack.
On pop or peek, if the outgoing stack is empty, pop every item from incoming onto outgoing.
The outgoing top is the oldest item: pop removes it, peek just reads it.
Amortised O(1) per operation and O(n) space.
Moving items back and forth on every operation makes each one O(n).
Read the full guides first: Stacks, Queues and Deques.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.