232. Implement Queue using Stacks
Learn how to implement a queue using two stacks in Python for LeetCode 232, that tests your understanding of data structures. Discover an efficient solution with clear explanations and interactive visualization of how stack operations can simulate queue behavior.
LeetCode Link: 232. Implement Queue using Stacks
Problem Definition
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
).
Implement the MyQueue
class:
void push(int x)
Pushes element x to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returnstrue
if the queue is empty,false
otherwise.
Notes:
- You must use only standard operations of a stack, which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
Example 1:
Input:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output:
[null, null, null, 1, 1, false]
Explanation:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
Constraints:
1 <= x <= 9
- At most
100
calls will be made topush
,pop
,peek
, andempty
. - All the calls to
pop
andpeek
are valid.
Understanding the Challenge
The key challenge here lies in the fundamental difference between stacks and queues:
- A stack follows LIFO (Last In, First Out)
- A queue follows FIFO (First In, First Out)
To bridge this gap, we'll need to use two stacks: an input stack and an output stack. The interaction between these two stacks will help us achieve the FIFO behavior of a queue.
How It Works
Let's break down the key operations:
- Push Operation
- New elements are always pushed to the input stack
- This maintains the order of insertion
- Pop Operation
- If the output stack has elements, we pop from there
- If the output stack is empty, we transfer all elements from the input stack to the output stack
- This transfer reverses the order, effectively converting LIFO to FIFO
- Peek Operation
- Similar to pop, but we return the top element without removing it
- Uses the same transfer mechanism when necessary
Below is a CodeSandbox I created to illustrate:
Solution
class MyQueue:
def __init__(self):
"""
Initialize two stacks:
- stack_in: handles push operations
- stack_out: handles pop operations
"""
self.stack_in = [] # Input stack
self.stack_out = [] # Output stack
def push(self, x: int) -> None:
"""
Simply push new elements to the input stack
Time complexity: O(1)
"""
self.stack_in.append(x)
def pop(self) -> int:
"""
Pop the front element from the queue
Time complexity: Amortized O(1)
"""
# Handle empty queue case
if self.empty():
return None
# If output stack has elements, pop from there
if self.stack_out:
return self.stack_out.pop()
# If output stack is empty, transfer all elements from input stack
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
"""
Return the front element without removing it
Time complexity: Amortized O(1)
"""
if self.empty():
return None
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out[-1]
def empty(self) -> bool:
"""
Check if the queue is empty
Time complexity: O(1)
"""
return len(self.stack_in) == 0 and len(self.stack_out) == 0
Conclusion
This problem demonstrates how to simulate a queue using stacks. It emphasizes problem-solving with constrained resources and showcases techniques for efficient code reuse. The Python implementation is intuitive and leverages helper functions for better clarity and maintainability.
Discussion