Tensorum
LeetCode 232 · Stack / Queue Design

Implement Queue using Stacks

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

Make push expensive so the oldest item stays on top.

EasyStackDesignQueue
58 msruntime · beats 1%
48.4 MBmemory · beats 100%
1approach
1accepted runs · last 1 Apr 2024

This is how I solved Implement Queue using Stacks (LeetCode 232), 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

Keep stackOne ordered so its top is always the front of the queue. To push, pour everything into stackTwo, put the new item at the bottom of stackOne, and pour everything back on top. Then pop and peek are just the top of stackOne.

Approach

  1. 1

    push: move stackOne → stackTwo, push x, move everything back.

  2. 2

    pop: pop stackOne.

  3. 3

    peek: read stackOne's top.

  4. 4

    empty: stackOne has no items.

How I solved it

Costly pushPythonO(n) push
class MyQueue:
    def __init__(self):
        self.stackOne = []
        self.stackTwo = []

    def push(self, x):
        while self.stackOne:
            self.stackTwo.append(self.stackOne.pop())
        self.stackOne.append(x)
        while self.stackTwo:
            self.stackOne.append(self.stackTwo.pop())

    def pop(self):
        if not self.stackOne:
            return False
        return self.stackOne.pop()

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

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

Implement Queue using Stacks — FAQ

What is the intuition behind Implement Queue using Stacks?

Keep stackOne ordered so its top is always the front of the queue. To push, pour everything into stackTwo, put the new item at the bottom of stackOne, and pour everything back on top. Then pop and peek are just the top of stackOne.

How do you solve Implement Queue using Stacks (LeetCode 232)?

1. push: move stackOne → stackTwo, push x, move everything back. 2. pop: pop stackOne. 3. peek: read stackOne's top. 4. empty: stackOne has no items.

What is the time and space complexity of Implement Queue using Stacks?

Time: O(n) push, O(1) pop/peek. Space: O(n). (Accepted approach: Costly push.)

What are common mistakes in Implement Queue using Stacks?

The amortised two-stack version makes pop O(1) amortised instead.