15% off all plans & roadmaps Use code

See plans

Implement Queue using Stacks

Updated

TL;DR: Build a first-in, first-out queue using only stack operations. Keep one stack for pushes and one for pops, and move elements across only when the output stack runs empty.

Problem

You need a first in, first out (FIFO) queue built from stacks. Your class must support push, pop, peek, and empty.

You may use only stack operations: push to top, peek or pop from top, size, and is-empty. A Python list or a deque can stand in for a stack, as long as you touch only the top.

Implement the MyQueue class:

  • void push(int x) pushes element x to the back of the queue.
  • int pop() removes the element at 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.

Example 1

Input: ["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output: [null, null, null, 1, 1, false]
Explanation: After the first push the queue is [1]. After the second push it is [1, 2], with 1 at the front. peek returns 1. pop returns 1, leaving [2]. empty returns false.

Constraints

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All calls to pop and peek are valid.

Constraints that matter

  • At most 100 calls means brute force finishes well within limits, so the real test is the amortized bound the follow-up asks for.
  • Values are between 1 and 9, so a plain int stack holds every value. The values themselves never affect the algorithm.
  • Every pop and peek call is valid. You never need an error branch for an empty queue in those methods.
  • Only stack operations are allowed. Removing from the front of a list costs O(n), and a deque's front removal breaks the rule.

View on LeetCode

Hints

Hint 1

A stack returns the newest element first, and a queue returns the oldest element first.

Hint 2

A beginner keeps one stack whose top is the front of the queue.

Solution

Intuition

A stack returns the newest element first, and a queue returns the oldest element first. Pushing values onto one stack and then popping them onto a second stack reverses their order. That reversal is the step you need.

It is like flipping a stack of unsorted mail onto a second pile. The input stack is the incoming pile, and the output stack is the pile you read from, so the oldest letter sits on top.

This is a design problem. You wrap two stacks behind a fixed interface, and the real decision is when to move data between them. Pick that moment carefully and the moves average out to constant time per call. That averaging is amortized analysis, and it is what the follow-up asks for.

The statement restricts you to stack operations, so you cannot index into a list or remove from its front. The stacks must do the reordering for you. Reorder only when a read forces it. Once an element reaches the output stack, it stays there until it leaves.

Watch the pattern animation

Worked example

Input: operations = ["MyQueue", "empty"], values = [[], []]
Output: [null, true]
Explanation: The constructor runs first and returns null. The new queue has no elements, so empty() returns true. Both stacks are empty at that point.

Approach 1: Brute force: rebuild on every push

A beginner keeps one stack whose top is the front of the queue. A push then has to place the new value at the bottom, because it is the newest and belongs at the back. The only way to reach the bottom is to lift every element off, put the new value down, and place the old elements back on top. The pop and peek methods then read the top directly.

Steps

  1. Keep one stack stack where the top holds the front of the queue.
  2. In push, pop every element off stack onto a helper stack.
  3. Push x onto stack. It is the only element there, so it sits at the bottom.
  4. Pop everything from the helper back onto stack. The old front returns to the top.
  5. pop and peek read or remove the top. empty checks whether stack has elements.

Dry run

The page example has no pushes, so start with the empty stack. A new MyQueue has stack = [], and empty() returns true. The output is [null, true], which matches the verified example.

For a trace with pushes, use Example 1 from the statement. After push(1) the stack holds [1], with 1 on top. For push(2), the 1 moves to the helper, the 2 goes down, and the 1 returns on top, so the stack reads [2, 1] from bottom to top. peek() returns 1. pop() returns 1 and leaves [2]. empty() returns false. The output is [null, null, null, 1, 1, false].

Complexity

TimeO(n) per push, O(1) for pop, peek, and empty
SpaceO(n)

Let n be the number of elements in the queue. A push moves each of the n elements to the helper and back, which is about 2n stack operations. The pop, peek, and empty methods touch only the top, so each does constant work. The two stacks hold n values in total, so the space is O(n).

PythonTested in our runner

class MyQueue:
    def __init__(self):
        # The top of this list is the front of the queue
        self.stack = []

    def push(self, x: int) -> None:
        helper = []
        # Move everything aside so x can sit at the bottom
        while self.stack:
            helper.append(self.stack.pop())
        self.stack.append(x)
        while helper:
            self.stack.append(helper.pop())

    def pop(self) -> int:
        return self.stack.pop()

    def peek(self) -> int:
        return self.stack[-1]

    def empty(self) -> bool:
        return len(self.stack) == 0

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Two stacks with lazy transferOptimalDesign (General/Specific)

What's slow: the brute force rebuilds the whole stack on every push, even when nobody reads the queue. Most of that work is wasted, because a value that is only pushed never needs to reach the front.

The insight that fixes it: keep pushes on an input stack with no reordering at all. Move elements to an output stack only when pop or peek needs the front and the output stack is empty.

The transfer reverses the input once, so the oldest element lands on top. Elements stay on the output stack until they leave.

Why it is correct. The invariant is that the output stack holds the oldest elements in reading order, and every element in the input stack is newer than all of them. When outStack is empty, moving everything from inStack reverses the input, so the oldest element ends on top. Elements already on outStack never need to move again, so its top is always the correct front.

Steps

  1. Create inStack for pushes and outStack for reads.
  2. In push(x), push x onto inStack and do nothing else.
  3. In pop and peek, if outStack is empty, pop everything from inStack and push each value onto outStack.
  4. In pop, pop and return the top of outStack. In peek, return that top without removing it.
  5. In empty, return true only when both stacks are empty.

Dry run

The page example, verified, is empty() on a new queue. The table has one row per step.

StepCallinStack (bottom to top)outStack (bottom to top)Returns
0constructor[][]null
1empty()[][]true

The output is [null, true].

For Example 1 from the statement, the trace is longer:

StepCallinStackoutStackReturns
1push(1)[1][]null
2push(2)[1, 2][]null
3peek(), outStack empty, move 2 then 1[][2, 1]1
4pop(), outStack not empty, pop its top[][2]1
5empty(), outStack still holds 2[][2]false

The output is [null, null, null, 1, 1, false].

Complexity

TimeO(1) amortized for push, pop, peek, and empty. A single pop or peek can take O(n).
SpaceO(n)

Let n be the number of pushes in a sequence of calls. Each value moves from inStack to outStack at most once, and it never moves back. A transfer costs time proportional to the number of values it moves, so all transfers together cost at most n moves. Spreading the O(n) total over the calls gives O(1) amortized per call, and the two stacks hold at most n values, so the space is O(n).

PythonTested in our runner

class MyQueue:
    def __init__(self):
        self.input_stack = []   # new elements land here
        self.output_stack = []  # the top is the front of the queue

    def push(self, x: int) -> None:
        self.input_stack.append(x)

    def _transfer_if_needed(self) -> None:
        # Move elements only when the front is needed and output is empty
        if not self.output_stack:
            while self.input_stack:
                self.output_stack.append(self.input_stack.pop())

    def pop(self) -> int:
        self._transfer_if_needed()
        return self.output_stack.pop()

    def peek(self) -> int:
        self._transfer_if_needed()
        return self.output_stack[-1]

    def empty(self) -> bool:
        return not self.input_stack and not self.output_stack

Common mistakes

  • Moving elements back to inStack after each read, for example inStack.push(outStack.pop()) inside pop. Each call then costs O(n). Keep elements on outStack until they leave.
  • Transferring when outStack is not empty, for example if inStack is not empty inside pop. Newer elements land on top of older ones, so the front is wrong. Transfer only when outStack is empty.
  • Checking only inStack in empty, as in return not inStack. Elements still waiting on outStack are queued. Check both stacks.
  • Reading the front with list[0] or removing it with pop(0). That costs O(n) and breaks the stack-only rule. Read the top with [-1] or the stack's peek.
  • Putting the transfer only in pop, not in peek. Then peek returns a stale value from the input side or fails on an empty output stack. Call one shared helper from both methods.
  • Pushing new values straight onto outStack. The new value lands on top, which is the front, so pop returns the newest value instead of the oldest.

Edge cases

  • A single push followed by a pop: push(5), then pop() returns 5, and empty() returns true afterwards.
  • A peek between pushes: push(1), peek() returns 1, push(2), pop() returns 1, then pop() returns 2.
  • Repeated values: push(3) twice, then two pops return 3 and 3. Order follows insertion time, not value.
  • Draining the queue: after pop empties outStack, empty() must still return false while inStack holds values.
  • empty() on a new queue: returns true with no transfer and no reads.
  • A long run of up to 100 pushes followed by 100 pops: the values come back in the exact order they went in.

Follow-ups interviewers ask

Why is the amortized bound O(1) when one pop can cost O(n)?
A transfer moves every element in the input stack at once, and that can be many elements. Each element crosses from the input stack to the output stack once and never comes back. So the total number of moves across all calls is at most the number of pushes. Spreading that total over the calls gives O(1) each.
Can you solve it with one stack and recursion instead?
Yes. To remove the oldest element, recurse until you reach the bottom of the stack, take that value, and push the rest back on the way up. Each pop costs O(n), and deep recursion can overflow the call stack for large queues. The two stack version keeps the amortized bound and avoids deep recursion.
What changes if several threads call these methods?
Both pop and peek can move elements and change outStack, so a single lock around each method is the safe choice. Without a lock, two threads can interleave a transfer and corrupt both stacks. A lock-free design is much harder and is not needed for this problem.

Implement Queue using Stacks FAQ

What is the time complexity of Implement Queue using Stacks?

With the lazy transfer, push is O(1), and pop, peek, and empty are O(1) amortized. A single pop can take O(n) when it moves elements. Over a sequence of n calls the total work is O(n).

Why use two stacks for Implement Queue using Stacks?

A stack reverses order, and two reversals restore first-in, first-out order. The input stack stores new values without reordering them. The output stack gives you the oldest value on top after each transfer.

Can Implement Queue using Stacks be solved in O(1) extra space?

No, the queue must hold all of its values, so total space is O(n). Beyond those stored values, the lazy approach needs no extra container, so its auxiliary space is O(1). The brute force approach also uses only the two stacks it needs, so both stay within O(n) total.

Can I use Python's deque for Implement Queue using Stacks?

A deque with popleft would solve the problem in one line, but the statement allows only stack operations. Use a list with append and pop() from the end, both of which are O(1). Calling pop(0) on a list is O(n) and will be slow on large inputs.

What is the difference between Implement Queue using Stacks and Implement Stack using Queues?

The first problem reverses order with two stacks, while the second reverses order with queues. Both use a transfer step to flip the order. The stack-from-queue version needs to rotate elements on every push in its simple form.

Asked at

See which companies ask this — Pro

Practise it