Implement Queue Using Stacks, explained

To build a first-in, first-out queue from two last-in, first-out stacks, push new items onto an inbox stack and serve pops from an outbox stack. Only when the outbox is empty do you pour the whole inbox into it, which reverses the order so the oldest item ends up on top. A single pop can cost O(n), but every item is moved at most once, so any sequence of n operations costs O(n) in total: amortized O(1) per operation.

By Published 8 min read

The task, restated

Implement a queue with four methods. push(x) adds x at the back. pop() removes and returns the value at the front. peek() returns the front value without removing it. empty() says whether the queue holds anything. The catch: internally you may only use stacks, and only through their standard operations, pushing onto the top, popping from the top, reading the top, and checking size or emptiness. A Python list or JavaScript array is fine as a stack as long as you only touch its end.

A made-up script, with the two stacks shown bottom to top
CallReturnsinboxoutbox
push(1)[1][]
push(2)[1, 2][]
peek()1[][2, 1]; poured, 1 is on top
push(3)[3][2, 1]
pop()1[3][2]
pop()2[3][]
push(4)[3, 4][]
pop()3[][4]; poured again
empty()false[][4]
pop()4[][]
empty()true[][]
A made-up script, with the two stacks shown bottom to top. Scroll sideways on a small screen.

Watch row four. The 3 is pushed while the outbox still holds 2 and 1, and it waits in the inbox. That is correct: 1 and 2 arrived earlier and must leave first. Pouring 3 on top of them would put it ahead of them, which is the most common bug in this problem.

Ask whether pop and peek can be called on an empty queue. In the usual version they cannot, so the code can assume a value exists. If they can, decide together whether to return a sentinel or raise an error.

Why interviewers like it

The code is tiny, so the question works as a warm-up, but it hides the cleanest example of amortized analysis in the whole interview canon. Strong candidates explain why a pop that sometimes takes O(n) still averages O(1), and they can say what amortized does and does not promise. It also comes up in functional programming, where a queue built from two immutable lists is a standard structure, and in systems talk about batching work. Typical follow-ups include:

  • Prove the amortized bound. Count the stack operations each item ever takes part in; there are at most four.
  • Is any single operation O(1) worst case? Push and empty are. Pop and peek are not, and a latency-sensitive system might care.
  • Now build a stack from queues. One queue is enough if you rotate it after each push; see the follow-up below.
  • Add a size method. It is the sum of both stack sizes.

A slow baseline: shuffle on every pop

Keep everything in one main stack in arrival order, so the front of the queue is at the bottom. To pop, move every item onto a helper stack, which exposes the oldest on top, pop it, then move everything back. Each pop and peek costs O(n) and the back-and-forth work is repeated every time. The mirror image, doing the shuffle on push so that the oldest item always sits on top, makes pop O(1) and push O(n). Both are correct; neither is the answer the interviewer wants.

class ShuffleQueue:
    def __init__(self):
        self.main = []
        self.helper = []

    def push(self, x):
        self.main.append(x)

    def pop(self):
        while self.main:
            self.helper.append(self.main.pop())
        front = self.helper.pop()
        while self.helper:
            self.main.append(self.helper.pop())
        return front

    def empty(self):
        return not self.main
Python: correct, but every pop moves the whole queue twice.

Optimal approach: an inbox and an outbox

The waste in the baseline is moving items back. Skip that step. Once items have been poured into the second stack they are already in queue order, oldest on top, so leave them there and serve pops from it until it runs dry. New pushes go to the first stack meanwhile. Only an empty outbox triggers a pour, and a pour always moves the entire inbox, which keeps the order right.

class StackQueue:
    def __init__(self):
        self.inbox = []
        self.outbox = []

    def push(self, x):
        self.inbox.append(x)

    def _refill(self):
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop())

    def pop(self):
        self._refill()
        return self.outbox.pop()

    def peek(self):
        self._refill()
        return self.outbox[-1]

    def empty(self):
        return not self.inbox and not self.outbox
Python: lists used strictly as stacks.
class StackQueue {
  constructor() {
    this.inbox = [];
    this.outbox = [];
  }

  push(x) {
    this.inbox.push(x);
  }

  refill() {
    if (this.outbox.length === 0) {
      while (this.inbox.length > 0) this.outbox.push(this.inbox.pop());
    }
  }

  pop() {
    this.refill();
    return this.outbox.pop();
  }

  peek() {
    this.refill();
    return this.outbox[this.outbox.length - 1];
  }

  empty() {
    return this.inbox.length === 0 && this.outbox.length === 0;
  }
}
JavaScript: arrays touched only at the end.

Both versions share one helper for pop and peek, so the pouring rule lives in exactly one place. Note that empty() must check both stacks; checking only the outbox reports an empty queue while items still sit in the inbox.

The amortized argument, in plain words

Follow a single item through its life. It is pushed onto the inbox once, popped off the inbox once during a pour, pushed onto the outbox once, and popped off the outbox once when it leaves the queue. That is four stack operations, ever, no matter how many other items come and go. So if you perform n queue operations, the total number of stack operations is at most about four per item pushed plus a constant per call, which is O(n). Divide by n and each operation costs O(1) on average over the sequence.

Be precise about what that means. Amortized O(1) is a guarantee about the total cost of any sequence, not about a single call, and it does not depend on luck or random input. One unlucky pop after a million pushes still does a million moves. If the interviewer asks about a hard real-time system, say that a worst-case O(1) queue would need a different design, such as a ring buffer.

Follow-up: a stack from one queue

The reverse question is common. With a single queue, push the new item at the back, then rotate: pop from the front and push to the back size - 1 times. The new item is now at the front, so pop and top are plain queue operations. Push becomes O(n) and pop O(1), and there is no amortized trick this time, because each rotation really does touch every item.

from collections import deque

class QueueStack:
    def __init__(self):
        self.line = deque()

    def push(self, x):
        self.line.append(x)
        for _ in range(len(self.line) - 1):
            self.line.append(self.line.popleft())

    def pop(self):
        return self.line.popleft()

    def top(self):
        return self.line[0]

    def empty(self):
        return not self.line
Python: deque used only through append, popleft and len.

Time and space

n items currently in the queue
Designpushpop / peekSpace
Shuffle on every popO(1)O(n)O(n)
Shuffle on every pushO(n)O(1)O(n)
Inbox and outboxO(1)O(1) amortized, O(n) worst single callO(n)
Stack from one queue (follow-up)O(n)O(1)O(n)
n items currently in the queue. Scroll sideways on a small screen.

Edge cases

  • A fresh queue: empty() is true, and pop or peek should not be called unless the interviewer defines a behavior for it.
  • Strictly alternating push and pop: every pop pours exactly one item, which is still O(1).
  • All pushes first, then all pops: the first pop pours everything, the rest are instant.
  • Peek followed by pop returns the same value both times; peek may trigger the pour, pop then finds the outbox ready.
  • Repeated values: the structure never compares values, so duplicates need no special care.

Mistakes to avoid

  • Pouring the inbox into the outbox when the outbox is not empty, which puts newer items ahead of older ones.
  • Moving items back to the inbox after each pop, which throws away the amortized benefit.
  • Checking only one stack in empty().
  • Using list.pop(0) or Array.prototype.shift, which reads from the bottom and breaks the stack-only rule.
  • Saying pop is O(1) without the word amortized, then struggling when asked about the worst case.

How to explain it out loud

Fictional example

Getting to the amortized point quickly
Candidate
Pushes go onto an inbox stack. Pops and peeks come off an outbox stack. When the outbox is empty I pour the inbox into it, which reverses the order so the oldest item is on top.
Candidate
I never pour into a non-empty outbox, because the items already there are older than anything in the inbox.
Candidate
A pour can take linear time, but each item gets poured once in its life: pushed, moved, popped. So n operations cost O of n total, amortized constant each, and push is constant even in the worst case.

Design Circular Queue reaches worst-case O(1) for every queue operation with a fixed array, which is the answer if the interviewer pushes on latency. Basic Calculator is the next step up in stack skills: the stack there saves a whole computation in progress, not just a value. Valid Parentheses is the gentlest stack problem if you want a warm-up first.

Practicing it with Natively

The amortized explanation is where practice pays off, and Natively helps you hear yourself. On a Mac or Windows PC it transcribes a mock session and saves the transcript, so you can check whether you said amortized and explained why. It can also read a problem like this from a screenshot during practice and draft a solution to compare against. The AI interview assistant page shows the workflow.

Questions people ask

How do you implement a queue using two stacks?

Push new items onto an inbox stack. To pop or peek, serve from an outbox stack, and when the outbox is empty, pour the whole inbox into it, which puts the oldest item on top.

Why is a queue from two stacks amortized O(1)?

Each item is pushed onto the inbox, moved to the outbox, and popped from the outbox once in its life, so n operations cost O(n) in total even though a single pop can take O(n).

What is the worst-case time of one pop?

O(n), when the outbox is empty and the inbox holds n items. Push is O(1) in the worst case.

How do you implement a stack using a queue?

After pushing a new item to the back of a single queue, rotate the queue by moving size - 1 items from front to back. The newest item is then at the front, so pop and top are O(1) and push is O(n).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP