Implement Queue using Stacks — LeetCode 232 Python Solution

EasyStackDesignQueue
Problem
#232
Pattern
Stack
Reading time
6 min

The problem

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Example

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
Output
[null, null, null, 1, 1, false]
Explanation
MyQueue myQueue = new MyQueue();

Python solution

Python
class MyQueue:
    def __init__(self):
        self.stk1 = []
        self.stk2 = []

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

    def pop(self) -> int:
        self.move()
        return self.stk2.pop()

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

    def empty(self) -> bool:
        return not self.stk1 and not self.stk2

    def move(self):
        if not self.stk2:
            while self.stk1:
                self.stk2.append(self.stk1.pop())


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

Complexity

MeasureComplexity
TimeO(1)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 232. Implement Queue using Stacks is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack and Queue.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on Grind 75.

Frequently asked questions

How hard is LeetCode 232. Implement Queue using Stacks?
LeetCode 232. Implement Queue using Stacks is rated Easy on LeetCode.
What is the time complexity of LeetCode 232. Implement Queue using Stacks?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 232. Implement Queue using Stacks?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 232. Implement Queue using Stacks cover?
LeetCode 232. Implement Queue using Stacks is tagged Stack, Design and Queue on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview