#225
Implement Stack using Queues
EasyStackDesignQueueQueueData Structure Design
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can optimize the stack operations by maintaining the stack's top element in the first queue, allowing for constant time access to the top element and more efficient push and pop operations.
⚙️
Algorithm
4 steps- 1Step 1: For push, simply enqueue the new element to the first queue.
- 2Step 2: For pop, dequeue all elements except the last one, which is the top of the stack. Swap the queues afterward.
- 3Step 3: For top, perform the same transfer as in pop but keep the last element in the first queue.
- 4Step 4: For empty, check if the first queue is empty.
solution.py27 lines
1from collections import deque
2
3class MyStack:
4 def __init__(self):
5 self.q1 = deque()
6 self.q2 = deque()
7
8 def push(self, x):
9 self.q1.append(x)
10
11 def pop(self):
12 while len(self.q1) > 1:
13 self.q2.append(self.q1.popleft())
14 top_element = self.q1.popleft()
15 self.q1, self.q2 = self.q2, self.q1
16 return top_element
17
18 def top(self):
19 while len(self.q1) > 1:
20 self.q2.append(self.q1.popleft())
21 top_element = self.q1[0]
22 self.q2.append(self.q1.popleft())
23 self.q1, self.q2 = self.q2, self.q1
24 return top_element
25
26 def empty(self):
27 return len(self.q1) == 0ℹ
Complexity note: The time complexity is O(n) for pop and top operations because we may need to transfer n-1 elements between queues. However, push is O(1).
- 1Using two queues can simulate stack behavior effectively.
- 2Understanding the transfer of elements between queues is crucial for efficient operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.