Skip to content
Veltoryx Technologies
FreeProblem 56● EasyLeetCode #232 ↗4 min readUpdated 30 October 2026

Implement Queue using Stacks

Implement a FIFO queue using two LIFO stacks with amortized O(1) push, pop, and peek operations via lazy pouring.

01The problem

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

You must use only standard stack operations: push to top, peek/pop from top, size, and is empty.

Input OperationsOutputWhy
push(1), push(2), peek()11 was pushed first, so it is at the front
pop()1Removes and returns front element 1
empty()false2 remains inside the queue

Constraints: 1 <= x <= 9, at most 100 calls. All calls to pop and peek are valid.

02How to spot it

  • A queue requires FIFO order (first in, first out).
  • A stack provides LIFO order (last in, first out).
  • Pouring elements from one stack to another reverses their order: LIFO reversed becomes FIFO!
  • Pouring on every push or pop is expensive (O(n) per operation).
  • Solution: Maintain two stacks: an inbox and an outbox. Pour lazily only when outbox runs dry.

So: two stacks with lazy transfer.

03Pseudocode

text
push(x): in.push(x)
peek():
  if out empty:
    move everything from in to out
  return out.top
pop(): peek(); return out.pop()
empty(): both stacks empty
  1. New items always go into the in stack (inbox).
  2. Need the front item? Look in the out stack (outbox).
  3. If out is empty, pour all elements from in to out (reversing their order).
  4. Both stacks must be empty for the queue to be empty.

04Watch it work

Visualizer · step through the algorithmops = [["push",1],["push",2],["peek"],["pop"],["empty"]]

inbox stack (pushes)

outbox stack (pops/peeks)

operation

init

Queue using two stacks: `in` stack receives pushes, `out` stack serves pops and peeks in FIFO order.

Pseudocode

  1. push(x): in.push(x)
  2. peek():
  3. if out empty:
  4. move everything from in to out
  5. return out.top
  6. pop(): peek(); return out.pop()
  7. empty(): both stacks empty

Variables

in
out
step 1 / 7

05Step-by-step dry run

  1. 1

    inbox stack (pushes)

    outbox stack (pops/peeks)

    operation

    init

    Queue using two stacks: `in` stack receives pushes, `out` stack serves pops and peeks in FIFO order.

    in = out =

  2. 2

    inbox stack (pushes)

    10
    top

    outbox stack (pops/peeks)

    operation

    push(1)

    Push 1 onto inbox stack.

    op = pushval = 1

  3. 3

    inbox stack (pushes)

    10
    21
    top

    outbox stack (pops/peeks)

    operation

    push(2)

    Push 2 onto inbox stack.

    op = pushval = 2

  4. 4

    inbox stack (pushes)

    outbox stack (pops/peeks)

    20
    11
    top

    operation

    peek: pour in -> out

    Outbox is empty: poured all elements from inbox to outbox, reversing their order to FIFO.

    inCount = 0outCount = 2

  5. 5

    inbox stack (pushes)

    outbox stack (pops/peeks)

    20
    11
    top

    operation

    peek -> 1

    Peek front element: 1.

    front = 1

  6. 6

    inbox stack (pushes)

    outbox stack (pops/peeks)

    20
    top

    operation

    pop -> 1

    Popped front element 1 from outbox.

    popped = 1

  7. 7

    inbox stack (pushes)

    outbox stack (pops/peeks)

    20
    top

    operation

    empty -> false

    Check empty: false. Both stacks have elements.

    isEmpty = false

06Java solution

MyQueue.java
import java.util.ArrayDeque;
import java.util.Deque;

public class MyQueue {
    private final Deque<Integer> in = new ArrayDeque<>();
    private final Deque<Integer> out = new ArrayDeque<>();

    public void push(int x) {
        in.push(x);
    }

    public int pop() {
        peek();
        return out.pop();
    }

    public int peek() {
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.peek();
    }

    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }

    public static void main(String[] args) {
        MyQueue q = new MyQueue();
        q.push(1);
        q.push(2);
        System.out.println(q.peek());
        System.out.println(q.pop());
        System.out.println(q.empty());
    }
}
Expected output
1
1
false

07Why it works

Pouring from in to out flips the order of elements: the oldest element in in (at the bottom) becomes the newest element in out (at the top).

Crucially, we only pour when out is completely empty. If out already has elements, pouring new ones onto it would place newer elements above older elements, breaking FIFO order. By waiting until out empties, every element is transferred across the two stacks exactly once in its lifetime.

08Time and space

  • Time complexity:
    • push: O(1).
    • pop and peek: Amortized O(1), worst-case O(n). Each element is pushed onto in once, popped from in once, pushed onto out once, and popped from out once. Total work for n operations is 4n = O(n), averaging O(1) per call.
    • empty: O(1).
  • Space complexity: O(n) to store n elements distributed between the two stacks.

09Edge cases

  • Alternating pushes and pops: Correctly handled because push never touches out, and pop only drains in when out is empty.
  • Multiple peek calls in a row: The first peek pours elements; subsequent calls immediately return out.peek() in O(1).
  • Empty queue check: Must verify both stacks (in.isEmpty() && out.isEmpty()).

10Common mistakes

  • Refilling out when it is not empty. If out has elements and you pour in into it, the newer elements from in sit above older elements in out, corrupting FIFO order.
  • Transferring back from out to in on push. Some naive designs pour back and forth on every operation. That turns every push and pop into an expensive O(n) operation.

11Other approaches

ApproachPush timePop timeSpaceNote
Pour on pushO(n)O(1)O(n)Heavy push, always keeps elements in pop order
Lazy pour on pop/peekO(1)O(1) amortizedO(n)Optimal standard design

12In the interview

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why must we only pour elements from in to out when out is completely empty?

  2. 2. What is the amortized time complexity of pop() in this two-stack queue?

14Solve it yourself

Try implementing a stack using two FIFO queues (MyStack):

  1. How does the order reversal change when queues are the primitive?
  2. Can push or pop be O(1) amortized?