Implement Stack using Queues — LeetCode 225 Python Solution
- Problem
- #225
- Pattern
- Stack
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Example
- Input
- ["MyStack", "push", "push", "top", "pop", "empty"]
- Output
- [null, null, null, 2, 2, false]
- Explanation
- MyStack myStack = new MyStack();
Python solution
class MyStack:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.popleft()
def top(self) -> int:
return self.q1[0]
def empty(self) -> bool:
return len(self.q1) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of elements in the stack auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 225. Implement Stack using Queues 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
Frequently asked questions
- How hard is LeetCode 225. Implement Stack using Queues?
- LeetCode 225. Implement Stack using Queues is rated Easy on LeetCode.
- What is the time complexity of LeetCode 225. Implement Stack using Queues?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 225. Implement Stack using Queues?
- The Python solution on this page uses O(n), where n is the number of elements in the stack auxiliary space.
- What topics does LeetCode 225. Implement Stack using Queues cover?
- LeetCode 225. Implement Stack using Queues is tagged Stack, Design and Queue on LeetCode.