15% off all plans & roadmaps Use code

See plans

Implement Stack using Queues

Updated

TL;DR: You must build a LIFO stack from queues that only allow push to back and pop from front. Keep the newest element at the front by rotating the queue after each push, so pop and top run in O(1).

Problem

Implement a last-in-first-out (LIFO) stack using only two queues. The stack must support push, top, pop, and empty, the same operations a normal stack offers.

Implement the MyStack class:

  • void push(int x) pushes element x to the top of the stack.
  • int pop() removes the element on the top of the stack and returns it.
  • int top() returns the element on the top of the stack.
  • boolean empty() returns true if the stack is empty, false otherwise.

Notes:

  • You must use only standard queue operations. That means push to back, peek or pop from front, size, and is empty.
  • Your language may not provide a queue natively. You may simulate one with a list or deque, as long as you use only standard queue operations.

Example 1

Input: ["MyStack", "push", "push", "top", "pop", "empty"] and [[], [1], [2], [], [], []]
Output: [null, null, null, 2, 2, false]
Explanation: Create the stack, push 1, then push 2. top() returns 2. pop() returns 2. empty() returns false because 1 is still in the stack.

Constraints

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

Constraints that matter

  • Each pop and top call is valid, so you never need to handle an empty stack in those methods.
  • At most 100 calls means the stack holds at most 100 elements, so a method that costs O(n) per push is fast enough.
  • Values are between 1 and 9, so you do not need to think about overflow or special values.

View on LeetCode

Hints

Hint 1

A stack returns the newest element first.

Hint 2

Keep two queues.

Solution

Intuition

A stack returns the newest element first. A queue returns the oldest element first. The problem asks you to build last-in, first-out behaviour from a first-in, first-out container, so the real question is where the newest element can wait until it reaches the front.

Picture a queue as a checkout line where people join at the back and leave from the front. Each push is a newcomer joining, then everyone already waiting walks to the back one at a time, so the newcomer reaches the front.

This is an adapter pattern. You wrap one data structure in a class that exposes a different interface. Every method must work using only the queue's allowed operations, and that restriction decides the design.

The key observation is that a queue can rotate. Enqueue the new value, then dequeue and re-enqueue each older value once. The new value ends up at the front, and the older values stay in their original order behind it. After that, pop and top are each one queue operation.

Watch the pattern animation

Worked example

Input: commands: ["MyStack", "empty"], args: [[], []]
Output: [null, true]
Explanation: The constructor runs first and creates an empty stack. Calling empty() on that stack returns true. The dry runs below extend this example with a push, top, pop and empty sequence on the same object.

Approach 1: Two queues, copy on push

Keep two queues. The first queue, q1, holds the stack with the top at its front. The second queue, q2, is an empty helper between calls.

To push, add the new value to q2 first, then move every element of q1 behind it. Now the new value is at the front of q2 and the older values follow in order. Swap the two queues so that q1 is the stack again. Pop and top read the front of q1.

This is correct, and it is the natural first design. It copies the whole stack on every push, even though the stack changes by only one element. The helper queue exists only to hold that copy.

Steps

  1. Create two empty queues, q1 and q2.
  2. In push, enqueue x into q2.
  3. While q1 is not empty, dequeue from q1 and enqueue into q2.
  4. Swap the names of q1 and q2 so q1 holds the full stack again.
  5. In pop, dequeue from the front of q1 and return it.
  6. In top, return the front of q1 without removing it.
  7. In empty, return whether q1 has no elements.

Dry run

Start with q1 = [] and q2 = [] and run the example sequence push(1), push(2), top(), pop(), empty().

The lists below run from front to back.

CallActionq1 afterq2 afterReturn
MyStack()create both queues[][]
empty()q1 has no elements[][]true
push(1)q2 gets 1, q1 is empty, swap[1][]
push(2)q2 gets 2, then 1 moves from q1, swap[2, 1][]
top()read front of q1[2, 1][]2
pop()remove front of q1[1][]2
empty()q1 still holds 1[1][]false

The example output [null, true] comes from the first empty() call on the fresh stack.

Complexity

Timepush O(n), pop O(1), top O(1), empty O(1)
SpaceO(n)

Let n be the number of elements in the stack when you push. Push enqueues x into q2, then moves all n older elements from q1 to q2, about n + 1 queue operations of O(1) each, so push is O(n). Pop, top and empty each touch the front of one queue once, so they are O(1). Across both queues there are at most n stored elements, so space is O(n).

PythonTested in our runner

from typing import List, Optional
from collections import deque

class MyStack:
    def __init__(self):
        # q1 holds the stack, q2 is the helper
        self.q1 = deque()
        self.q2 = deque()

    def push(self, x: int) -> None:
        self.q2.append(x)
        while self.q1:
            self.q2.append(self.q1.popleft())
        self.q1, self.q2 = self.q2, self.q1

    def pop(self) -> int:
        return self.q1.popleft()

    def top(self) -> int:
        return self.q1[0]

    def empty(self) -> bool:
        return len(self.q1) == 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: One queue, rotate on pushOptimalDesign (General/Specific)

What's slow in the two-queue version is the helper queue. It exists only to hold a temporary copy of the stack, and every push pays to copy everything.

The insight that fixes it is that you do not need a copy. After you enqueue x at the back, the other n-1 elements are still in the queue in newest-to-oldest order. If you dequeue each of them from the front and enqueue it at the back, x moves forward past all of them and becomes the front. The relative order of the older elements stays the same.

Since the front is always the newest element, pop and top become single queue operations. All the work moves to push, where it is paid once per element.

Steps

  1. Create one queue q.
  2. In push, enqueue x at the back of q.
  3. Let n be the size of q. Repeat n-1 times: dequeue the front and enqueue it at the back.
  4. In pop, dequeue and return the front of q.
  5. In top, return the front of q without removing it.
  6. In empty, return whether q has no elements.

Dry run

Run the same sequence on one queue: push(1), push(2), top(), pop(), empty(). The lists run from front to back.

StepCallQueue before rotationRotation workQueue afterReturn
0MyStack()[]none[]
1empty()[]none[]true
2push(1)[1]n-1 = 0 moves[1]
3push(2)[1, 2]n-1 = 1 move: dequeue 1, enqueue 1[2, 1]
4top()[2, 1]none[2, 1]2
5pop()[2, 1]none[1]2
6empty()[1]none[1]false

Row 1 produces the example output's first value, true. Row 3 shows the single rotation that brings 2 to the front.

Complexity

Timepush O(n), pop O(1), top O(1), empty O(1)
SpaceO(n)

Let n be the number of elements in the stack when you push. Push enqueues one element and then performs n-1 dequeue and enqueue pairs, about 2n queue operations of O(1) each, so push is O(n). Pop, top and empty each perform one front operation, so they are O(1). The queue stores n elements and the rotation uses no other storage, so space is O(n).

PythonTested in our runner

from typing import List, Optional
from collections import deque

class MyStack:
    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        # Move the n-1 older elements behind x so x reaches the front
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self) -> int:
        return self.q.popleft()

    def top(self) -> int:
        return self.q[0]

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

Common mistakes

  • Rotating n times instead of n-1 in the one-queue push. After n rotations the queue is back in its original order, so x stays at the back. Rotate exactly n-1 times.
  • Reading q.back() in top(). A queue exposes only the front for reads, and the stack top is the front in the one-queue design.
  • Computing the rotation count inside the loop condition with a changing size, such as while (q.size() > 1) with a counter that never resets. Read n once before the loop and run n-1 steps.
  • Using list.pop(0) as the dequeue in Python. Removing from the front of a Python list costs O(n), which turns every pop into O(n). Use collections.deque with popleft.
  • In the two-queue version, swapping the local names but not the fields or references, so the next call reads the empty queue. Update the stored queues after the swap.

Edge cases

  • Call empty() on a new stack. The answer is true, and no queue operation should fail.
  • Push one value, then pop it. The stack is empty afterwards, and empty() returns true. In the one-queue design, the rotation runs zero times for the first push.
  • Push the same value twice, such as 5 then 5. Both copies stay in the stack, and two pops return 5 and then 5.
  • Push up to 100 values, then pop them all. The last pop returns the first value pushed, and every value comes back in reverse order.
  • Push, pop, then push again. The new value must become the top, and it must not return an old value left in the queue.

Follow-ups interviewers ask

Can you make push O(1) and pay the cost in pop instead?
Yes. Keep the queue in plain insertion order and let pop rotate the queue until the newest element reaches the front. Pop then costs O(n) and top still needs the back element, which means a rotation too. The total work across operations stays in the same order, so the choice depends on which call the caller makes more often.
Can you implement the stack using only one queue?
Yes. The one-queue rotation approach on this page does exactly that. It keeps one queue, rotates it on each push, and reads the front for top and pop.
What if the stack must hold millions of values?
Memory is still O(n), and that cannot change for a stack of n values. The rotation cost becomes the bottleneck, because each push moves up to n values. At that scale you would use a real stack or a ring buffer and skip the rotation entirely.

Implement Stack using Queues FAQ

What is the time complexity of Implement Stack using Queues?

Push is O(n) in the one-queue design, where n is the current stack size, because it rotates n-1 elements. Pop, top and empty are each O(1). The two-queue design has the same bounds.

Why use queue rotation for Implement Stack using Queues?

Rotation moves the newest element to the front of the queue, which is the only position a queue lets you read or remove. Once the newest element is at the front, every stack operation maps to a single queue operation. The adapter pattern makes this possible without any random access.

Can Implement Stack using Queues be solved in O(1) extra space?

Yes, in the sense that the rotation uses only one temporary value and no auxiliary structure. The stored elements still take O(n) space, because the stack must hold them. The two-queue version uses a second queue, which is also O(n) in the worst case.

Why does Python need deque for this problem?

A Python list removes from the front in O(n), so each pop or rotation step would cost linear time. A deque supports popleft and append in O(1). Using a deque keeps the queue operations constant time.

Asked at

See which companies ask this — Pro

Practise it