Queues

First in, first out: the structure behind breadth-first search, level-order traversal, ring buffers and the monotonic deque for sliding window maximum.

Overview

A queue is a line. You add at the back (enqueue) and take from the front (dequeue), so the item that waited longest leaves first: FIFO, first in, first out. Reach for one whenever items must be handled in the order they arrived, or when everything at distance d must be finished before anything at distance d + 1.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

What a queue is

The rule: use a deque. All four basic operations on it cost O(1).

  • Python: collections.deque. Enqueue with q.append(x), dequeue with q.popleft(), peek with q[0], test for empty with not q.
  • Java: ArrayDeque through the Queue interface. Enqueue with q.offer(x), dequeue with q.poll(), peek with q.peek(), test for empty with q.isEmpty().

> [!WARNING] > Never use a Python list as a queue: list.pop(0) shifts every remaining element, so it costs O(n). In Java, poll() and peek() return null on an empty queue, while remove() and element() throw.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio