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
, pop
, peek
, 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 whether the queue is empty.Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.push
and pop
operations.We’ll use two stacks to simulate the queue:
Operations:
in_stack
.out_stack
is empty, pop all elements from in_stack
and push them onto out_stack
(this reverses the order, simulating FIFO).out_stack
.True
if both in_stack
and out_stack
are empty.This approach ensures that we always get the front element in O(1)
average time, while pushes are O(1)
and pops are amortized O(1)
due to potential transfer between stacks.
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())
in_stack
.out_stack
is empty, elements are transferred from in_stack
in O(n) time, but each individual element is popped only once.pop
, but no elements are removed.This implementation efficiently simulates a queue using two stacks, ensuring all operations adhere to the required time complexities.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?