algoritmauzmanı
Sign in
TREN
5.6More Queues and Applications
Lesson 5.6.2

A queue from two stacks

A removes the last element in; a 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.

What you will learn
  • How to write and with an inbox and an outbox stack
  • Why elements are moved only when the outbox is empty
  • Why the cost is O(1) even though one dequeue can take O(n)
7 minTime O(1)Memory O(n)C · Java · Python

1Idea

The idea: enqueue always does a onto the inbox stack. dequeue always does a 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:

  1. It is pushed onto inbox once.
  2. It is popped from inbox once.
  3. It is pushed onto outbox once.
  4. It is popped from outbox once.

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.

Operationinbox (top on the right)outbox (top on the right)Stack operations
enqueue 1, 2, 31 2 3empty3
dequeue → 1empty3 23 moved (6) + 1 pop = 7
enqueue 443 21
dequeue → 2431
dequeue → 34empty1
dequeue → 4emptyempty1 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.

inboxoutbox12343214
  1. Three enqueues. Each is one push onto inbox. 3 is on top; the oldest element, 1, is at the bottom.
  2. dequeue. outbox is empty, so the move starts. 3 is popped from the top of inbox and pushed onto outbox.
  3. The move goes on: 2, then 1 take the same path. inbox is empty. The top of outbox now holds the oldest element, 1.
  4. Pop from outbox: 1 is returned. The first element of the queue came out, as it should.
  5. enqueue(4). 4 goes to inbox. outbox is not touched; 2 and 3 are waiting there.
  6. dequeue. outbox is not empty, so nothing is moved. 2 is popped from the top. One step.
  7. dequeue. Again nothing is moved. 3 is returned and outbox is empty.
  8. dequeue. outbox is empty, so the 4 in inbox is 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

Time
O(1)

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).

Memory
O(n)

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?

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?

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.