Sub topic 12
Building a Stack from Queues and a Queue from Stacks
Assume you know FIFO and LIFO behavior, queue and stack operations, Big-O notation, and basic object references. This chapter uses two standard transformations:
- A stack removes the most recently inserted item.
- A queue removes the least recently inserted item.
The challenge is to preserve one ordering while using structures with the other ordering.
Stack using two queues
Let q1 be the main queue and q2 be a helper queue. To implement a stack with costly push:
- Insert the new item into
q2. - Move every item from
q1toq2. - Swap the names of
q1andq2.
The newest item is now at the front of q1, so pop is simple.
| Operation | Cost with costly `push` |
|---|---|
| `push` | O(n) |
| `pop` | O(1) |
| `top` | O(1) |
from collections import deque
class StackUsingQueues:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, value):
self.q2.append(value)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self):
if not self.q1:
raise IndexError("stack is empty")
return self.q1.popleft()
def top(self):
if not self.q1:
raise IndexError("stack is empty")
return self.q1[0]
stack = StackUsingQueues()
for value in [10, 20, 30]:
stack.push(value)
print(stack.pop()) # 30An alternative makes push O(1) and moves items during pop. The total behavior differs per operation, but the design still uses two queues.
Queue using two stacks
Let in_stack receive new items and let out_stack provide removals.
enqueue(x)pushesxontoin_stack.- For
dequeue, ifout_stackis empty, move every item fromin_stacktoout_stack. - Pop from
out_stack.
Reversing the items once changes their LIFO order into FIFO order.
With this design, each item moves from in_stack to out_stack at most once.
| Operation | Worst-case cost | Amortized cost |
|---|---|---|
| `enqueue` | O(1) | O(1) |
| `dequeue` | O(n) | O(1) |
Amortized cost means the average cost over a long sequence of operations. A single dequeue can move many items, but those items cannot be moved again until they are newly enqueued.
GATE-style reasoning
For a stack implemented with two queues, identify which operation preserves the newest item at the front. For a queue implemented with two stacks, check whether transfer happens only when the output stack is empty. Then count each item movement, rather than assuming every operation has the same cost.
Exercise
A queue uses two stacks. The input stack contains [1, 2, 3], with 3 at the top, and the output stack is empty. What is returned by the next dequeue, and what are the top-to-bottom contents of the output stack afterward?
Show answer
The items are transferred, reversing their order. The dequeue returns 1, and the output stack contains [2, 3], with 2 at the top.