00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each item is moved from in to out at most once, so although a single dequeue can move many items, the average cost per operation is constant.

Approaches

Both versions give the same order. The lazy version transfers only when needed; the eager version keeps the stack in queue order at all times.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of items. In the lazy version each item is pushed and popped twice in total, giving amortised O(1); the eager version pays O(n) on every enqueue.

Interview Tips and Recommended Approach

  • Transfer only when out is empty. Transferring earlier breaks the order.
  • Explain amortised analysis: each element moves between stacks at most once.
  • Know the reverse question. A stack from two queues needs O(n) push or pop.
  • Use ArrayDeque for both stacks in Java.

Recommended Approach: Lazy Transfer

Why: it gives constant average time per operation and is the classic example of amortised analysis.