Implement a first-in first-out queue with push, pop, peek and empty, using only two stacks and their standard operations.
Before you code
Pouring one stack into another reverses its order, and reversing LIFO order gives FIFO order. The question is when to pour, so that no item is moved more than necessary.
Hints
inboxreceives every push.outboxserves every pop and peek.- Only when
outboxis empty, move everything frominboxtooutbox. Its top is then the oldest item. - Each item is pushed onto
inboxonce, moved once and popped fromoutboxonce, so n operations cost O(n) in total: O(1) amortized, even though a single pop can take O(n).
Production & complexity notes
When solving Implement queue using stacks on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Queues and ring buffers to reinforce the underlying pattern.
What it practices
FIFO order and amortized cost, from Queues and ring buffers. In practice you would use a ring buffer; this problem is about reasoning with the two orders.