push(1), push(2), peek(), pop(),
push(3), peek(), pop(), pop(), empty()[None, None, 1, 1, None, 2, 2, 3, True]A queue stores items in arrival order: first in, first out (FIFO). Add at the back, read or remove from the front.
Imagine a ticket counter. A arrives, then B, then C. Nobody jumps ahead: A is served first. New arrivals join the back while the front keeps moving.
The key idea
The front is always the oldest waiting item. Use a queue when work should be processed in the order it arrives.
Process waiting jobs, count recent requests, simulate a ticket line, or explore a tree level by level with BFS.
Build MyQueue using two stacks. push(x) adds x at the back; pop() removes and returns the front; peek() returns the front without removing it; empty() returns whether the queue is empty. Use only stack operations: push to the top, pop or peek at the top, size, and checking for emptiness.
push(1), push(2), peek(), pop(),
push(3), peek(), pop(), pop(), empty()[None, None, 1, 1, None, 2, 2, 3, True]The values leave in arrival order: 1, 2, 3. peek reads a value but leaves it in the queue.
empty(), push(4), peek(), peek(), pop(), empty()[True, None, 4, 4, 4, True]Calls start with a new queue. Push values are integers from 1 to 9. pop and peek are called only on a nonempty queue. None marks an operation without a return value.
LeetCode 232 ↗push(1), push(2), peek(), pop(), push(3), peek(), pop(), pop(), empty() [None, None, 1, 1, None, 2, 2, 3, True]
Each push moves the n stored values out and back. pop, peek, and empty use only the top or an emptiness check.
The two stacks together store n queue values. Moving a value does not create another queue entry.
push(1), push(2), peek(), pop(), push(3), peek(), pop(), pop(), empty() [None, None, 1, 1, None, 2, 2, 3, True]
Unlike rearranging on every push, lazy transfer never moves a value back to inbox. That avoids repeated work while preserving FIFO order.
Each value enters inbox once, moves to outbox at most once, and leaves once. So m operations take O(m) total time. One pop or peek can still take O(n) when it triggers a transfer; amortized means averaged over a sequence.
The two stacks together store n queue values. Moving a value does not create another queue entry.