Tensorum
LeetCode 225 · Stack / Queue Design

Implement Stack using Queues

LeetCode 225 · Easy · solution, intuition & step-by-step walkthrough

Rotate after each push so the newest is at the front.

EasyStackDesignQueue
53 msruntime · beats 0%
48.6 MBmemory · beats 100%
1approach
3accepted runs · last 10 Apr 2024

This is how I solved Implement Stack using Queues (LeetCode 225), an easy problem from the Stack / Queue Design pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.

Approach

  1. 1

    push: enqueue x, then move the other n−1 elements behind it.

  2. 2

    pop: dequeue the front.

  3. 3

    top: peek the front.

  4. 4

    empty: queue is empty.

How I solved it

Single queue, rotate on pushPythonO(n) push
from collections import deque


class MyStack:
    def __init__(self):
        self.Q1 = deque()
        self.Q2 = deque()

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

    def pop(self):
        if not self.Q1:
            return None
        return self.Q1.popleft()

    def top(self):
        if not self.Q1:
            return None
        return self.Q1[0]

    def empty(self):
        return len(self.Q1) == 0
Loading the step-through…

Implement Stack using Queues — FAQ

What is the intuition behind Implement Stack using Queues?

A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.

How do you solve Implement Stack using Queues (LeetCode 225)?

1. push: enqueue x, then move the other n−1 elements behind it. 2. pop: dequeue the front. 3. top: peek the front. 4. empty: queue is empty.

What is the time and space complexity of Implement Stack using Queues?

Time: O(n) push, O(1) pop/top. Space: O(n). (Accepted approach: Single queue, rotate on push.)

What are common mistakes in Implement Stack using Queues?

One queue is enough; the two-queue version is commented out in the code.