← Back to Algorithms, page 2

algorithms-0035 · Easy fresher

Implement a FIFO queue with O(1) enqueue and dequeue, and then build the same queue using only two stacks.

A queue is first in, first out. list.pop(0) is O(n) because every element shifts, so use collections.deque, whose popleft is O(1). With two stacks, push onto an inbox stack; when the outbox is empty, move everything across, which reverses the order. Each element moves at most once, so dequeue is amortised O(1).

Full answer

Problem

Implement Queue with enqueue(x), dequeue(), peek() and len(), all O(1). Then implement QueueFromStacks using only two Python lists used as stacks (append and pop at the end).

Example: a ticket counter: enqueue T1, T2, T3; dequeue gives T1; enqueue T4; the next three dequeues give T2, T3, T4.

Constraints: up to 10^5 operations; dequeue on an empty queue raises IndexError.

Brute force

A Python list with append and pop(0). Correct, but pop(0) shifts all remaining elements, so it is O(n) per dequeue and O(n^2) for n operations.

Optimal approach

Queue: back it with collections.deque; append adds to the back and popleft removes from the front, both O(1).

QueueFromStacks:

  1. enqueue pushes onto in_stack.
  2. dequeue: if out_stack is empty, pop everything from in_stack and push it onto out_stack, reversing the order. Then pop from out_stack.
  3. Raise IndexError if both stacks are empty.

Why it works

Reversing a stack once turns its last-in order into first-in order. Elements in out_stack are always older than elements in in_stack, so serving out_stack first keeps FIFO order. Moving only when out_stack is empty preserves that property.

Amortised cost: each element is pushed onto in_stack once, moved once and popped from out_stack once, so n operations cost O(n) total, even though a single dequeue can cost O(n).

Complexity

Deque version: O(1) per operation. Two-stack version: O(1) amortised, O(n) worst case for one dequeue. Both O(n) space.

Code

python
from collections import deque


class Queue:
    """FIFO queue backed by collections.deque: enqueue and dequeue are O(1)."""

    def __init__(self):
        self._items = deque()

    def enqueue(self, item):
        self._items.append(item)

    def dequeue(self):
        if not self._items:
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()

    def peek(self):
        if not self._items:
            raise IndexError("peek from empty queue")
        return self._items[0]

    def __len__(self):
        return len(self._items)


class QueueFromStacks:
    """Queue built from two stacks; each element moves at most once: amortised O(1)."""

    def __init__(self):
        self._in, self._out = [], []

    def enqueue(self, item):
        self._in.append(item)

    def dequeue(self):
        if not self._out:
            while self._in:
                self._out.append(self._in.pop())   # reverse order once
        if not self._out:
            raise IndexError("dequeue from empty queue")
        return self._out.pop()

    def __len__(self):
        return len(self._in) + len(self._out)


if __name__ == "__main__":
    for Q in (Queue, QueueFromStacks):
        q = Q()
        for token in ("T1", "T2", "T3"):
            q.enqueue(token)
        assert q.dequeue() == "T1"
        q.enqueue("T4")
        assert [q.dequeue() for _ in range(3)] == ["T2", "T3", "T4"]
        assert len(q) == 0
        try:
            q.dequeue()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    q = Queue()
    q.enqueue(1)
    assert q.peek() == 1 and len(q) == 1
    print("all tests passed")

Save as a35_queue.py and run python3 a35_queue.py. It prints all tests passed (Python 3.13.5).

Edge cases

Dequeue or peek on an empty queue raise IndexError. Interleaved enqueues and dequeues (the test enqueues T4 after a dequeue). Moving elements while out_stack still has items would break the order.

Pattern

Queue (FIFO) and amortised analysis. Queues drive breadth-first search, task scheduling and buffering; the two-stack trick also builds a min queue from two min stacks.

python
from collections import deque


class Queue:
    """FIFO queue backed by collections.deque: enqueue and dequeue are O(1)."""

    def __init__(self):
        self._items = deque()

    def enqueue(self, item):
        self._items.append(item)

    def dequeue(self):
        if not self._items:
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()

    def peek(self):
        if not self._items:
            raise IndexError("peek from empty queue")
        return self._items[0]

    def __len__(self):
        return len(self._items)


class QueueFromStacks:
    """Queue built from two stacks; each element moves at most once: amortised O(1)."""

    def __init__(self):
        self._in, self._out = [], []

    def enqueue(self, item):
        self._in.append(item)

    def dequeue(self):
        if not self._out:
            while self._in:
                self._out.append(self._in.pop())   # reverse order once
        if not self._out:
            raise IndexError("dequeue from empty queue")
        return self._out.pop()

    def __len__(self):
        return len(self._in) + len(self._out)


if __name__ == "__main__":
    for Q in (Queue, QueueFromStacks):
        q = Q()
        for token in ("T1", "T2", "T3"):
            q.enqueue(token)
        assert q.dequeue() == "T1"
        q.enqueue("T4")
        assert [q.dequeue() for _ in range(3)] == ["T2", "T3", "T4"]
        assert len(q) == 0
        try:
            q.dequeue()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    q = Queue()
    q.enqueue(1)
    assert q.peek() == 1 and len(q) == 1
    print("all tests passed")

Queue on collections.deque and QueueFromStacks with lazy transfer; both pass the same FIFO tests.

Complexity

Time: O(1) per operation; two-stack dequeue is O(1) amortised, O(n) worst case. Space: O(n). Each element is moved between the stacks at most once.

By level

Fresher: Implements the deque queue, explains why list.pop(0) is slow and traces the ticket example. Should test interleaved enqueue and dequeue calls.

Mid: Implements the two-stack queue with lazy transfer and gives the amortised argument. Explains the difference between amortised and worst-case cost.

Senior: Discusses worst-case latency of the two-stack queue, ring buffers, bounded queues with backpressure and thread-safe options such as queue.Queue. Can explain when one slow dequeue in the two-stack version matters for latency.

Key points

  • Queue is first in, first out
  • list.pop(0) is O(n); deque.popleft is O(1)
  • Two stacks: move only when the outbox is empty
  • Each element moves once: amortised O(1)
  • Raise on empty dequeue

Common mistakes

  • Using list.pop(0) in a hot loop
  • Transferring on every dequeue
  • Moving elements while the outbox is non-empty
  • Confusing amortised with worst-case time

Follow-ups

  • How would you implement a stack with queues?
  • How would you build a circular buffer of fixed size?
  • Where do queues appear in graph algorithms?

Tips

  • Say why pop(0) is slow
  • Explain the reversal step with a small trace
  • Define amortised cost clearly

Evaluation rubric

  • Correct FIFO behaviour
  • O(1) operations with deque
  • Correct two-stack logic
  • Correct amortised analysis