Implement Queue Using Stacks Problem
Description
LeetCode Problem 232.
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.
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 100calls will be made to push, pop, peek, and empty.
- All the calls to pop and peek are valid.
Solution
Approach: Input Stack and Output Stack
Pouring a stack into another stack reverses its order, so the element pushed first ends up on top, where a queue needs it. We keep two stacks:
inStack: everypushgoes here.outStack: holds elements in queue order, with the front of the queue on top.
pop() and peek() read from outStack. If outStack is empty, first move every element from inStack to it (pop from one, push onto the other). empty() is true when both stacks are empty.
Only refill outStack when it is empty. If it still holds elements, they are older than anything in inStack, and pouring new elements on top of them would break the order.
Example: push 1, push 2. inStack = [1, 2] (top on the right). peek() finds outStack empty and moves both, giving outStack = [2, 1], so the top is 1. pop() returns 1.
Complexity: push and empty take O(1) time. pop and peek take O(1) amortized time: each element is moved from inStack to outStack at most once. The stacks use O(n) space, where n is the number of elements in the queue.
class MyQueue:
def __init__(self):
self.in_stack = [] # new elements are pushed here
self.out_stack = [] # elements in front-of-queue order: the top is the front
def push(self, x: int) -> None:
self.in_stack.append(x)
def pop(self) -> int:
self._move_if_needed()
return self.out_stack.pop()
def peek(self) -> int:
self._move_if_needed()
return self.out_stack[-1]
def empty(self) -> bool:
return not self.in_stack and not self.out_stack
def _move_if_needed(self) -> None:
# Refill only when out_stack is empty; moving reverses the order, so the oldest ends on top.
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
Now write it from memory
Close the write-up and solve it yourself against the tests.