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
Difficulty
and has an acceptance rate of about 71% (1+ million submissions).
Typical patterns to solve this problem:
- Design
- Queue
- Stack
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 232: Implement Queue using Stacks
Solved On The Same Day
- problem 29: Divide Two Integers
- problem 57: Insert Interval
Extra
- 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