Sub topic 12
Building a stack from queues and a queue from stacks
This chapter assumes you know the stack and queue ADTs (push/pop, enqueue/dequeue), can write basic Python classes, and can count operations in Big-O terms. It covers the standard GATE question: given only one structure's operations, build the other and state the cost of each operation.
The core problem
A stack is LIFO and a queue is FIFO. Each one reverses the order the other produces. To build one from the other, you reorder elements by moving them between structures. Every design below decides where that moving happens: during the insert or during the remove.
The rules of the exercise are strict. You may call only the primitive operations of the underlying structure. For a stack these are push, pop, peek and is_empty. For a queue these are enqueue, dequeue, front and is_empty. You may not index into the underlying structure or iterate over it.
A queue from two stacks
Use two stacks, inbox and outbox. New items always go onto inbox. Removals come from outbox. When outbox is empty and a removal is requested, pop every item from inbox and push it onto outbox. That transfer reverses the order, so the oldest item ends up on top of outbox.
class QueueFromStacks:
def __init__(self):
self.inbox = [] # list used as a stack: append = push, pop = pop
self.outbox = []
def enqueue(self, x):
self.inbox.append(x)
def _transfer(self):
if not self.outbox:
while self.inbox:
self.outbox.append(self.inbox.pop())
def dequeue(self):
self._transfer()
if not self.outbox:
raise IndexError('queue empty')
return self.outbox.pop()
def front(self):
self._transfer()
if not self.outbox:
raise IndexError('queue empty')
return self.outbox[-1]
def is_empty(self):
return not self.inbox and not self.outbox
q = QueueFromStacks()
for v in [1, 2, 3]:
q.enqueue(v)
print(q.dequeue()) # 1
q.enqueue(4)
print(q.dequeue()) # 2
print(q.dequeue()) # 3
print(q.dequeue()) # 4The transfer happens only when outbox is empty. If you transferred on every dequeue, or moved items while outbox still held some, you would break the order. Items in outbox are older than every item in inbox, so they must leave first.
Cost of the two-stack queue
enqueue costs O(1). A single dequeue costs O(n) in the worst case, because it may move all n items. The amortized cost is O(1). Each item is pushed onto inbox once, popped from it once, pushed onto outbox once and popped from it once. That is at most four stack operations per item over its whole lifetime, regardless of how calls are interleaved.
GATE questions often ask for the worst-case count of stack operations for a specific sequence. Do not apply the amortized bound there. Trace the sequence and count each push and pop.
The costly-enqueue variant
You can instead keep one stack always ordered with the oldest item on top. To enqueue, move everything to a helper stack, push the new item onto the empty main stack, then move everything back. Now dequeue is a single pop, costing O(1), while enqueue costs O(n) every time. This version has no amortization benefit, so it is usually the worse choice. It appears in exam questions because the per-operation costs are easy to state.
A stack from queues
A queue cannot be reversed by a transfer to a second queue, because moving items between queues preserves their order. So you need a different trick: rotate the queue so that the newest item reaches the front.
One queue, costly push
Enqueue the new item, then dequeue and re-enqueue the n items that were already there. The new item is now at the front, which makes it the stack top.
from collections import deque
class StackFromQueue:
def __init__(self):
self.q = deque() # used only through append (enqueue) and popleft (dequeue)
def push(self, x):
n = len(self.q)
self.q.append(x)
for _ in range(n):
self.q.append(self.q.popleft())
def pop(self):
if not self.q:
raise IndexError('stack empty')
return self.q.popleft()
def peek(self):
if not self.q:
raise IndexError('stack empty')
return self.q[0]
def is_empty(self):
return not self.q
s = StackFromQueue()
for v in [1, 2, 3]:
s.push(v)
print(s.pop()) # 3
print(s.pop()) # 2
print(s.pop()) # 1push costs O(n) and pop costs O(1). Pushing onto a stack that already holds n items takes one enqueue plus n dequeue/enqueue pairs, which is 2n + 1 queue operations in total.
Two queues
The two-queue form does the same work with a helper. For a costly push, enqueue the new item into the empty queue q2, then move every item of q1 into q2, then swap the names of the two queues. For a costly pop, keep all items in q1. To pop, move all but the last item to q2, dequeue the last item from q1 as the result, then swap the names.
| Design | Push | Pop |
|---|---|---|
| Two queues, costly push | O(n) | O(1) |
| Two queues, costly pop | O(1) | O(n) |
| One queue, costly push (rotation) | O(n) | O(1) |
Unlike the two-stack queue, none of these designs achieves O(1) amortized time for both operations. Any sequence of n alternating pushes and pops on a stack with n items already in it pays the linear cost each time in the costly operation.
Tracing an example
Start with empty inbox and outbox and run: enqueue 1, enqueue 2, dequeue, enqueue 3, dequeue, dequeue. Show each stack with its top on the right.
- After the two enqueues:
inbox = [1, 2],outbox = []. - First dequeue:
outboxis empty, so transfer. Pop 2 and push it, then pop 1 and push it. Nowinbox = [],outbox = [2, 1]. Pop 1 and return it. - Enqueue 3:
inbox = [3],outbox = [2]. - Second dequeue:
outboxis not empty, so pop 2 with no transfer. - Third dequeue:
outboxis empty, so transfer 3, then pop it.
Counting stack operations: 2 pushes for the enqueues, then 2 pops and 2 pushes for the first transfer, 1 pop for the result, 1 push for enqueue 3, 1 pop for the second dequeue, then 1 pop and 1 push for the last transfer and 1 pop for the result. The total is 12.
Common errors
- Transferring on every dequeue. This breaks FIFO order when
outboxstill holds items, and it destroys the amortized bound. - Forgetting that
frontandpeekmay also trigger a transfer in the two-stack queue. - Checking emptiness on only one stack. The queue is empty only when both are empty.
- Claiming the stack-from-queues designs are amortized O(1). They are not.
- Counting a "swap of queue names" as a cost. It is a pointer exchange and takes O(1).
- Using the wrong size when counting. In a costly push onto n existing items, the rotation count is n, not n + 1.
Summary of costs
| Construction | Operation | Worst case | Amortized |
|---|---|---|---|
| Queue from two stacks (lazy transfer) | enqueue | O(1) | O(1) |
| Queue from two stacks (lazy transfer) | dequeue | O(n) | O(1) |
| Queue from two stacks (costly enqueue) | enqueue | O(n) | O(n) |
| Queue from two stacks (costly enqueue) | dequeue | O(1) | O(1) |
| Stack from queues (costly push) | push | O(n) | O(n) |
| Stack from queues (costly push) | pop | O(1) | O(1) |
Exercise
A queue is built from two stacks using the lazy-transfer design. Starting empty, you perform: enqueue 1, enqueue 2, enqueue 3, dequeue, enqueue 4, dequeue, dequeue, dequeue. How many push and pop operations on the stacks happen in total, and in what order do the items leave?
Show answer
Items leave in the order 1, 2, 3, 4. Count the operations. The three enqueues give 3 pushes. The first dequeue transfers 3 items (3 pops and 3 pushes), then pops 1 for the result, giving 7 operations. Enqueue 4 is 1 push. The second dequeue pops 2 from outbox (1 operation). The third dequeue pops 3 (1 operation). The fourth dequeue finds outbox empty, transfers item 4 (1 pop and 1 push), then pops it (1 operation), giving 3 operations. Total: 3 + 7 + 1 + 1 + 1 + 3 = 16 operations.
Exercise
A stack is built from a single queue with a costly push. The stack already holds 5 items. How many queue operations does the next push take, and what is the cost of a pop?
Show answer
The push does 1 enqueue, then 5 dequeue/enqueue pairs, which is 1 + 5 × 2 = 11 queue operations, so O(n). A pop is a single dequeue, which is O(1), because the newest item is already at the front.