Difficulty: Easy | Acceptance: 69.70% | Paid: No Topics: Stack, Design, Queue
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() Returns true 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, and is 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.
-
Examples
-
Constraints
Examples
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 to push, pop, peek, and empty.
All the calls to pop and peek are valid.
Two Stacks - Amortized O(1)
Intuition Use two stacks where one acts as input and the other as output. Elements are transferred between stacks only when needed, making operations amortized O(1).
Steps
- Maintain two stacks:
inStackfor push operations andoutStackfor pop/peek operations - When pushing, simply push to
inStack - When popping or peeking, if
outStackis empty, transfer all elements frominStacktooutStack(this reverses the order) - Then pop or peek from
outStack - Check if both stacks are empty for the
emptyoperation
class MyQueue:
def __init__(self):
self.in_stack = []
self.out_stack = []
def push(self, x: int) -> None:
self.in_stack.append(x)
def pop(self) -> int:
self._transfer()
return self.out_stack.pop()
def peek(self) -> int:
self._transfer()
return self.out_stack[-1]
def empty(self) -> bool:
return not self.in_stack and not self.out_stack
def _transfer(self) -> None:
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())Complexity
- Time: Amortized O(1) for all operations. Each element is pushed and popped from each stack exactly once.
- Space: O(n) where n is the number of elements in the queue
- Notes: This is the optimal solution with amortized constant time complexity for all operations.
Two Stacks - O(1) Push
Intuition Always keep elements in the correct order by transferring elements during push operations, making push O(n) but pop and peek O(1).
Steps
- Maintain two stacks:
mainStackandtempStack - When pushing, transfer all elements from
mainStacktotempStack, push the new element tomainStack, then transfer back fromtempStack - When popping or peeking, simply pop or peek from
mainStack - Check if
mainStackis empty for theemptyoperation
class MyQueue:
def __init__(self):
self.main_stack = []
self.temp_stack = []
def push(self, x: int) -> None:
while self.main_stack:
self.temp_stack.append(self.main_stack.pop())
self.main_stack.append(x)
while self.temp_stack:
self.main_stack.append(self.temp_stack.pop())
def pop(self) -> int:
return self.main_stack.pop()
def peek(self) -> int:
return self.main_stack[-1]
def empty(self) -> bool:
return not self.main_stackComplexity
- Time: O(n) for push, O(1) for pop, peek, and empty
- Space: O(n) where n is the number of elements in the queue
- Notes: This approach makes push expensive but pop and peek constant time. Useful when pop/peek operations are more frequent than push operations.