What Is a Queue?

A queue is a First-In, First-Out (FIFO) data structure. The first element you add is the first one out — like a queue at a coffee shop: first person in line gets served first.

Queue — FIFO1front23backDe-queue→ 1En-queueEnqueue 1 → [1]Enqueue 2 → [1, 2]Enqueue 3 → [1, 2, 3] Dequeue → returns 1

Core Operations

OperationDescriptionTime
enqueue(item)Add item to the backO(1)
dequeue()Remove and return frontO(1)
front()View front without removingO(1)
is_empty()Check if queue has itemsO(1)

Use Python's collections.deque or Java's ArrayDeque — not a plain list/array, because removing from the front of an array is O(N).


Implementation

Loading...

Interactive Lab

Simulation not available for this algorithm.

Queue vs Stack — Quick Comparison

PropertyQueue (FIFO)Stack (LIFO)
AddBackTop
RemoveFrontTop
MetaphorLine at a counterStack of plates
Algorithm useBFSDFS, recursion

The Ring Buffer (Circular Queue)

A common implementation uses a fixed-size circular array. Instead of shifting elements (O(N)), use head and tail index pointers that wrap around:

Ring Buffer — Capacity 4[0]_[1]B[2]C[3]Dhead=1tail=0wraps!After: Enqueue A,B → Dequeue (→A) → Enqueue C,Dtail = (3+1) % 4 = 0 — wraps without shifting elementsO(1) dequeue — no element shifting needed

This is how O(1) dequeue is achieved in the C implementation above.


Key Applications

  • BFS traversal of graphs and trees (the queue drives the level-by-level expansion)
  • Task schedulers — OS process queues, print spoolers
  • Message queues — Kafka, RabbitMQ (async job processing)
  • Buffers — keyboard input buffer, network packet queue
  • Level-order tree traversal

Key Takeaway

Queues enforce fairness — whoever arrived first is served first. They're the backbone of BFS and any system that processes work in arrival order. Always use a deque (double-ended queue) or circular buffer implementation, never a plain array — otherwise your O(1) dequeue silently becomes O(N).