Problem 225

Abstract / Summary

Implement a stack using queue operations without using stack specific features.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0225.py

class MyStack:
    def __init__(self):
        self.queue = []

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

    def pop(self) -> int:
        # one almost full rotation
        x = self.queue.pop(0)
        for _ in range(len(self.queue)):
            self.queue.append(x)
            x = self.queue.pop(0)
        return x

    def top(self) -> int:
        result = self.pop()
        self.push(result)
        return result

    def empty(self) -> bool:
        return len(self.queue) == 0
22 lines | 537 bytes | submitted August 28, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (1+ million submissions).

Typical patterns to solve this problem:
  • Design
  • Queue
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a stack abstraction using a single Python list that is treated as a queue. The class MyStack offers the typical stack operations: push, pop, top, and empty. Internally, the list self.queue stores elements in insertion order, and the methods manipulate this list to emulate LIFO (last-in-first-out) behavior while only using queue-style operations.

Core Construction

The constructor initializes the internal storage:

def __init__(self):
    self.queue = []

At creation time the stack is empty, and the list is ready to receive elements.

Push Operation

The push method appends a new integer to the end of the list, which corresponds to the rear of a queue:

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

Appending is an O(1) operation in Python, ensuring that adding an element does not depend on the current size of the stack.

Pop Operation

The pop method removes and returns the most recently added element, reproducing stack semantics. It first extracts the element at the front of the list (the head of the queue) and then repeatedly rotates the remaining elements to bring the last inserted item to the front:

def pop(self) -> int:
    # one almost full rotation
    x = self.queue.pop(0)
    for _ in range(len(self.queue)):
        self.queue.append(x)
        x = self.queue.pop(0)
    return x

The initial pop(0) removes the element that was first inserted, storing it in x. The subsequent loop runs once for each remaining element. Inside the loop the stored value x is appended to the end of the list, and the next element at the front is removed and assigned to x. After the loop completes, x holds the element that was originally at the rear of the queue, which is the element that should be returned for a stack pop.

Top Operation

The top method retrieves the element at the top of the stack without permanently removing it. It leverages the existing pop logic to obtain the value, then immediately pushes it back:

def top(self) -> int:
    result = self.pop()
    self.push(result)
    return result

By re-inserting the popped value, the internal order of the queue is restored to its original state, preserving the stack’s contents.

Empty Check

The empty method reports whether the stack holds any elements by checking the length of the internal list:

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

A length of zero indicates that no items are present, matching the expected behavior of a stack’s emptiness test.

Edge Cases Handled

When the stack is empty, calling pop or top would attempt to access self.queue[0]. The implementation implicitly relies on Python’s list behavior: pop(0) on an empty list raises an IndexError. This exception signals that the operation cannot be performed on an empty stack, which aligns with typical stack semantics where underflow is an error condition.

If only a single element exists, the pop method’s loop iterates zero times because len(self.queue) is zero after the initial removal. Consequently, the method returns the sole element directly, correctly handling the minimal non-empty case.

Performance Optimizations Observed

The push method uses list.append, which is a highly optimized, amortized constant-time operation in CPython. This choice avoids the overhead of inserting at the front of the list, which would be costly.

During the pop operation, the algorithm performs a single rotation of the queue’s contents rather than repeatedly moving elements back and forth. By storing the element to be rotated in a temporary variable x and reusing it across iterations, the code minimizes the number of temporary objects created. The loop appends and removes elements in place, leveraging the list’s built-in methods that are implemented in C for speed.

The top method reuses the pop and push implementations instead of duplicating rotation logic. This reuse ensures that any internal optimizations present in those methods are automatically applied when retrieving the top element.

Overall, the design keeps the critical path of each operation as tight as possible while adhering to the constraint of using a single queue-like list as the underlying storage.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a line of toys waiting to get into a toy box. The box works like a special stack where the last toy you put in is always the first one to come back out. To make this happen with a simple line, the code does a bit of a trick. When you want to take a toy out, it takes every toy from the front of the line and moves them all the way to the back, one by one. It keeps spinning the toys around in a circle until the very last toy is finally at the front of the line so it can be picked up. If you just want to look at the top toy without taking it out, the code peeks at it by taking it out and then immediately putting it back into the line. To see if the box is empty, the code just checks if there are any toys left in the line.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 4.96 | σ = 1.73

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust TS Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim Python
everthis JS
fartem Ruby
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong TS
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim Python
everthis JavaScript
fartem Ruby
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong TypeScript
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
52 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Implement Stack using Queues (LeetCode 225) | Using single and 2 queues | Visuals and animations'
Nikhil Lohia 20 mins
Implement Stack using Queues (LeetCode 225) | Using single and 2 queues | Visuals and animations
YouTube video 'Implement Stack using Queues | Leetcode 225 | Stack | Queues | Day-5'
Ayushi Sharma 22 mins
Implement Stack using Queues | Leetcode 225 | Stack | Queues | Day-5
YouTube video '[Java] Leetcode 225. Implement Stack using Queues [Stack & Queue #1]'
Eric Programming 8 mins
[Java] Leetcode 225. Implement Stack using Queues [Stack & Queue #1]
YouTube video 'LeetCode 225: Implement Stack using Queues'
Engineering Digest 6 mins
LeetCode 225: Implement Stack using Queues
YouTube video 'Implement Stack using Queues | Leetcode 225 | C++ Solution'
Paritosh Wankhade 6 mins
Implement Stack using Queues | Leetcode 225 | C++ Solution
YouTube video 'Implement Stack using Queues | Leetcode 225 | Stack | Queue'
Nitesh Nanda 11 mins
Implement Stack using Queues | Leetcode 225 | Stack | Queue
YouTube video 'Implement Stack using Queues | Leetcode 225 | Stacks | Live coding session'
Coding Decoded 8 mins
Implement Stack using Queues | Leetcode 225 | Stacks | Live coding session
YouTube video '225. Implement Stack using Queues | LEETCODE EASY | TOP INTERVIEW QUESTIONS'
code Explainer 8 mins
225. Implement Stack using Queues | LEETCODE EASY | TOP INTERVIEW QUESTIONS
YouTube video 'Implement Stack using Queues | Queue 🔥 | Stack🔥| C++ | LeetCode 225'
Gantavya Malviya 8 mins
Implement Stack using Queues | Queue 🔥 | Stack🔥| C++ | LeetCode 225
YouTube video 'Daily Leetcode #1245: Aug 28, 2023 - 225. Implement Stack using Queues'
Programming Live with Larry 25 mins
Daily Leetcode #1245: Aug 28, 2023 - 225. Implement Stack using Queues
YouTube video '225. Implement Stack using Queues | Leetcode | Queue | DSA'
Coding with Tamilarasan 13 mins
225. Implement Stack using Queues | Leetcode | Queue | DSA
YouTube video '225 || Implement Stack using Queues || C++ || Leetcode Daily Challenge'
CodeFreaks 9 mins
225 || Implement Stack using Queues || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #765: May 05, 2022 - 225. Implement Stack using Queues'
Programming Live with Larry 18 mins
Daily Leetcode #765: May 05, 2022 - 225. Implement Stack using Queues
YouTube video 'Implement Stack using Queue | Leetcode 225'
Vizuara 15 mins
Implement Stack using Queue | Leetcode 225
YouTube video 'Implement Stack Using Queues - LeetCode 225 - Python'
Alpha-Code 16 mins
Implement Stack Using Queues - LeetCode 225 - Python
YouTube video '225. Implement Stack using Queues | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 13 mins
225. Implement Stack using Queues | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'LeetCode 225. Implement Stack using Queues (2 queues & 1 queue)'
Kacy Codes 5 mins
LeetCode 225. Implement Stack using Queues (2 queues & 1 queue)
YouTube video 'Implement Stack using Queues | LeetCode 225 (Stack using Queues) | Queue With Python | Python DSA'
Nidhi Chouhan 38 mins
Implement Stack using Queues | LeetCode 225 (Stack using Queues) | Queue With Python | Python DSA
YouTube video 'Leetcode 225: Implement Stack using Queues'
Algorithms Casts 18 mins
Leetcode 225: Implement Stack using Queues
YouTube video 'LeetCode 225 | Implement Stack using Queues | Java'
Sleepy Cracker 8 mins
LeetCode 225 | Implement Stack using Queues | Java
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 medium
3 solutions   August 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality