Implement a stack using queues. You should implement the following operations of a stack using standard queue operations:
push(x)
– Push element x onto stack.pop()
– Removes the element on top of the stack.top()
– Get the top element.empty()
– Return whether the stack is empty.Notes:
enqueue
, dequeue
, size
, and isEmpty
operations are allowed.Before proceeding, let’s clarify a few things:
queue
(like collections.deque
or queue.Queue
) to implement the solution?Let’s assume standard constraints and built-in Python queue
usage is allowed unless specified otherwise.
We can maintain two queues (q1
and q2
) to manage the stack operations effectively:
push(x)
):
x
to q2
.q1
and enqueue them to q2
.q1
and q2
.pop()
):
q1
(as it holds the current stack elements in the correct order).top()
):
q1
(peek without dequeuing).empty()
):
q1
is empty (using its isEmpty method).This will ensure that all stack operations are simulated using queue operations.
from collections import deque
class MyStack:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.popleft()
def top(self) -> int:
return self.q1[0]
def empty(self) -> bool:
return not self.q1
O(n)
- Since we move all elements from q1
to q2
and then swap.O(1)
- Direct dequeuing from q1
.O(1)
- Direct access to the front element of q1
.O(1)
- Checking if q1
is empty.This approach ensures that our stack operations are correctly managed using two queues, while keeping most operations efficient.
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?