5.6More Queues and Applications
A queue from two stacks
A stack removes the last element in; a queue removes the first. Even so, you can build a queue from two stacks: one collects new elements, the other hands them out. Moving elements from one stack to the other reverses their order, so the oldest one comes to the top. This question comes up a lot in interviews and exams.
1Idea
The idea: enqueue always does a push onto the inbox stack. dequeue always does a pop from the outbox stack. If outbox is empty, every element in inbox is first popped one by one and pushed onto outbox. This move reverses the order: the oldest element at the bottom of inbox ends up on top of outbox.
Elements are moved only when outbox is empty. If you move while outbox still holds elements, the new ones land on top of the old ones and the order breaks. Example: 2 and 3 wait in outbox, with 2 on top. If you move 4 now, 4 comes to the top and the queue hands out 4 instead of 2.
Why amortized O(1)?
A single dequeue can be expensive: if inbox holds n elements, the move takes n steps. But each element goes through at most four stack operations in its whole life:
- It is pushed onto
inboxonce. - It is popped from
inboxonce. - It is pushed onto
outboxonce. - It is popped from
outboxonce.
Once an element is in outbox it never goes back to inbox. So n enqueues and n dequeues take at most 4n stack operations in total, and the average per operation stays constant. One operation can take O(n) in the worst case, but over a long run of operations each one costs O(1). This is called amortized cost.
| Operation | inbox (top on the right) | outbox (top on the right) | Stack operations |
|---|---|---|---|
| enqueue 1, 2, 3 | 1 2 3 | empty | 3 |
| dequeue → 1 | empty | 3 2 | 3 moved (6) + 1 pop = 7 |
| enqueue 4 | 4 | 3 2 | 1 |
| dequeue → 2 | 4 | 3 | 1 |
| dequeue → 3 | 4 | empty | 1 |
| dequeue → 4 | empty | empty | 1 moved (2) + 1 pop = 3 |
That is 16 stack operations in total. For 4 elements this equals the limit 4 × 4 = 16. The second dequeue took 7 operations; the next two took only 1 each.
The C code builds the stacks on fixed-size arrays. When inbox is full, enqueue returns false, even if outbox has room. The Java and Python structures grow when needed, so they have no such limit.
2Step by step
1, 2 and 3 arrive in order. Then come four dequeues, with one enqueue in between. In each row the top of the stack is on the right.
- Three enqueues. Each is one push onto
inbox. 3 is on top; the oldest element, 1, is at the bottom. - dequeue.
outboxis empty, so the move starts. 3 is popped from the top ofinboxand pushed ontooutbox. - The move goes on: 2, then 1 take the same path.
inboxis empty. The top ofoutboxnow holds the oldest element, 1. - Pop from
outbox: 1 is returned. The first element of the queue came out, as it should. - enqueue(4). 4 goes to
inbox.outboxis not touched; 2 and 3 are waiting there. - dequeue.
outboxis not empty, so nothing is moved. 2 is popped from the top. One step. - dequeue. Again nothing is moved. 3 is returned and
outboxis empty. - dequeue.
outboxis empty, so the 4 ininboxis moved and popped. 4 is returned, and both stacks are empty.
#define CAPACITY 5 struct Queue { int inbox[CAPACITY]; // enqueue pushes here int outbox[CAPACITY]; // dequeue pops from here int topIn; // top of the inbox stack int topOut; // top of the outbox stack}; void create(struct Queue* q) { q->topIn = -1; q->topOut = -1;} bool isEmpty(struct Queue* q) { return q->topIn == -1 && q->topOut == -1;} bool enqueue(struct Queue* q, int value) { if (q->topIn == CAPACITY - 1) return false; // inbox is full q->inbox[++q->topIn] = value; // push return true;} bool dequeue(struct Queue* q, int* value) { if (isEmpty(q)) return false; if (q->topOut == -1) { // outbox empty: move while (q->topIn >= 0) q->outbox[++q->topOut] = q->inbox[q->topIn--]; // pop inbox, push outbox } *value = q->outbox[q->topOut--]; // pop outbox return true;}class TwoStackQueue { java.util.ArrayDeque<Integer> inbox = new java.util.ArrayDeque<>(); // enqueue pushes here java.util.ArrayDeque<Integer> outbox = new java.util.ArrayDeque<>(); // dequeue pops from here boolean isEmpty() { return inbox.isEmpty() && outbox.isEmpty(); } void enqueue(int value) { inbox.push(value); } int dequeue() { if (isEmpty()) throw new IllegalStateException("queue is empty"); if (outbox.isEmpty()) { // outbox empty: move while (!inbox.isEmpty()) outbox.push(inbox.pop()); } return outbox.pop(); }}class TwoStackQueue: def __init__(self): self.inbox = [] # enqueue pushes here self.outbox = [] # dequeue pops from here def is_empty(self): return not self.inbox and not self.outbox def enqueue(self, value): self.inbox.append(value) # push def dequeue(self): if self.is_empty(): raise IndexError("queue is empty") if not self.outbox: # outbox empty: move while self.inbox: self.outbox.append(self.inbox.pop()) return self.outbox.pop()The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
enqueue is always O(1). dequeue takes O(n) when a move is needed, but each element is moved at most once, so each operation costs amortized O(1).
The n elements are spread over the two stacks; O(n) space in total.
Amortized O(1) does not mean every operation is fast. In a real-time system a single O(n) dequeue can be a problem. There a circular queue or a linked-list queue is a better fit.
4Common mistake
The most common mistake is moving elements on every dequeue:
def dequeue(self): while self.inbox: # moves even if outbox is not empty self.outbox.append(self.inbox.pop()) return self.outbox.pop()While elements wait in outbox, the new ones land on top of them. If you add 1, 2, 3, do one dequeue and then add 4, the next dequeue returns 4 instead of 2. Tie the move to if not self.outbox:. Another mistake is checking only outbox for emptiness: elements may be waiting in inbox.
5Try it
You add 5, 6, 7 to an empty two-stack queue and do one dequeue. How many stack operations does that dequeue take?
The answer is C. outbox is empty, so three elements are moved: 3 pops and 3 pushes, 6 operations. Then one pop from outbox. 7 in total.
Show the answer
The answer is C. outbox is empty, so three elements are moved: 3 pops and 3 pushes, 6 operations. Then one pop from outbox. 7 in total.
Why are elements moved only when outbox is empty?
The answer is B. The elements waiting in outbox arrived before the new ones. If new elements land on top of them, a new one comes out first and the FIFO rule breaks.
Show the answer
The answer is B. The elements waiting in outbox arrived before the new ones. If new elements land on top of them, a new one comes out first and the FIFO rule breaks.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.