Foundation · Module 11 · Lesson 6

Stack/queue conversions

Implement one access discipline with another.

15–25 min readLesson 63 of 123

Lesson 63 of 123

1d streak

Interconversion: Implementing Queues with Stacks & Vice Versa

Implementing a Queue using Stacks (or a Stack using Queues) tests whether you understand how reversing access order works. Reversing a sequence twice restores its original arrival order: LIFO + LIFO = FIFO!

Implementing Queue with Two Stacks: inStack & outStack
Pushing elements (1, 2, 3):
  inStack:  [ 1, 2, 3 ] (top is 3)
  outStack: [ ]

When pop() or peek() is called:
If outStack is empty, transfer ALL elements from inStack to outStack:
  Pop 3 from inStack -> Push to outStack
  Pop 2 from inStack -> Push to outStack
  Pop 1 from inStack -> Push to outStack

Now:
  inStack:  [ ]
  outStack: [ 3, 2, 1 ] (top is 1! Exactly the FIFO order!)

Subsequent pop() simply pops from outStack in O(1)!
Amortized Cost per operation: O(1) time.
MyQueueUsingStacks.java
public class MyQueue {
    private Deque<Integer> inStack = new ArrayDeque<>();
    private Deque<Integer> outStack = new ArrayDeque<>();

    public void push(int x) {
        inStack.push(x); // O(1)
    }

    public int pop() {
        moveIfEmpty();
        return outStack.pop(); // Amortized O(1)
    }

    public int peek() {
        moveIfEmpty();
        return outStack.peek();
    }

    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }

    private void moveIfEmpty() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
    }
}

Cost Model

Complexity & Trade-offs

Operation sequence
O(1) amortized or O(n) worst
O(n)
The bound follows from the number of states visited and the work performed per transition.

When to use it

  • Nested parsing, undo, arrival order, buffering, and nearest-greater queries.
  • BFS frontiers and producer/consumer scheduling.
  • Maintaining range extremes or constrained access.

Common mistakes

  • Reading from an empty structure.
  • Confusing the logical front with an array index in a circular buffer.
  • Missing the amortized argument for transfers or monotonic pops.

Practice prompts

  • Reproduce the worked Stack/queue conversions example without looking at the trace.
  • Change one input condition and explain whether the Stack/queue conversions invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.