TRT
Sign in
easyFoundationsLeetCode#two stacks#lazy transfer

Implement queue using stacks

Build a FIFO queue from two LIFO stacks, and show that each operation is O(1) amortized.

The Runtime Theory Team1 min read
Taught inQueues and ring buffersA queue serves items in the order they arrived. Built on a ring buffer, a fixed array whose start and end wrap around, every operation is O(1) and no item ever moves.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inpush(1), push(2), peek(), pop(), empty()

out1, 1, false

inpush(1), pop(), empty()

out1, true

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

  1. inbox receives every push. outbox serves every pop and peek.
  2. Only when outbox is empty, move everything from inbox to outbox. Its top is then the oldest item.
  3. Each item is pushed onto inbox once, moved once and popped from outbox once, 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.

Not started

Sign in to save your learning progress.

Sign in to save