Previous Topic
underlying_implementation
0.88
Acts as the backing structure enabling efficient end-based operations required by queues.
fundamental_concept
0.85
Stacks and queues provide foundational knowledge of ordered data structures, with queues specifically illustrating the First In, First Out (FIFO) principle, which is crucial in various nursing and healthcare applications.

Queues

data structures algorithms operating systems software engineering networking concurrency distributed systems databases web development
A queue is a linear data structure and abstract data type that stores elements in the order they are added and retrieves them in first-in, first-out (FIFO) order. Queues support operations like enqueue (insert), dequeue (remove), and peek (inspect the next element). They are foundational in computer science and widely used in algorithms, operating systems, networking, and distributed systems to model pipelines, scheduling, and buffering.

What Is a Queue?

A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle: the earliest inserted element is the first one removed. Think of a line at a ticket counter—people are served in the order they arrive.

Core Operations

  • enqueue(x): Insert element x at the back (tail) of the queue.
  • dequeue(): Remove and return the element at the front (head). Often raises underflow if empty.
  • front() / peek(): Return the element at the front without removing it.
  • isEmpty(): Return whether the queue has no elements.
  • size(): Return the number of elements.

How Queues Work

Queues maintain two conceptual ends: a front from which elements are removed, and a rear to which new elements are added. This ordering naturally supports workflows where tasks arrive over time and must be processed in arrival order.

Implementations

  • Array-based: Fixed-size or dynamic arrays with head and tail indices. Circular buffering avoids shifting elements.
  • Linked list: Nodes linked in sequence with pointers to head and tail; grows until memory limits.
  • Circular queue: Array where head/tail wrap around using modular arithmetic.
  • Two-stack queue: Implements FIFO using two LIFO stacks, achieving amortized O(1) enqueue/dequeue.

Algorithmic Complexity

  • enqueue: O(1) average; O(n) worst if resizing (dynamic array).
  • dequeue: O(1) average; O(n) worst if shifting (avoid by circular buffer or linked list).
  • peek/front: O(1).
  • space: O(n) for n stored elements.

Variants and Related Structures

  • Deque (double-ended queue): Insert/remove at both ends.
  • Priority queue: Removes highest-priority element first (not strictly FIFO; often implemented with a heap).
  • Blocking queue: Thread-safe queue where enqueue/dequeue can block until space/data is available.
  • Lock-free/Wait-free queues: Concurrency-friendly queues using atomic operations for high throughput.

Common Use Cases

  • Scheduling: CPU round-robin scheduling, print spoolers, task dispatchers.
  • Traversal: Breadth-first search (BFS) in graphs and level-order traversal in trees.
  • Buffering: I/O buffers, network packet queues, streaming data pipelines.
  • Producer-consumer: Decoupling data producers from consumers in concurrent systems.
  • Messaging: Message queues in distributed, event-driven architectures.

Concurrency and Systems Considerations

  • Thread safety: Use synchronized or lock-free queues to avoid race conditions.
  • Backpressure: Bounded queues help signal when producers outpace consumers.
  • Fairness: FIFO ordering provides predictable service; priority or weighted queues can tune fairness vs. latency.
  • Throughput vs. latency: Batch dequeueing can improve throughput at the cost of per-item latency.

Example Pseudocode

// Interface
Queue:
  enqueue(x)
  y = dequeue()
  y = front()
  b = isEmpty()
  n = size()

// Breadth-First Search using a queue
function BFS(graph, start):
  q ← new Queue()
  visited ← empty set
  enqueue(q, start)
  add start to visited
  while not isEmpty(q):
    v ← dequeue(q)
    for each u in graph.neighbors(v):
      if u not in visited:
        add u to visited
        enqueue(q, u)

Gotchas and Best Practices

  • Underflow/overflow: Check for empty on dequeue/peek; for bounded queues, check for full on enqueue.
  • Circular buffer bugs: Watch off-by-one errors and correct modulo arithmetic.
  • Amortized vs. worst-case: Understand resizing costs for dynamic arrays.
  • Memory management: In linked implementations, ensure nodes are properly freed or garbage-collected.

Comparison to Stacks

Stacks are LIFO (last-in, first-out) and support backtracking and function call management; queues are FIFO and support fair scheduling and level-wise processing. Many systems use both, each where its ordering semantics best fit the problem.


Context from Referenced By

Context from Related Topics
Pop Quiz
Topic: queues
Level: 1
True or False:

A queue implemented with two stacks can perform both enqueue and dequeue in amortized constant time.

Topic: queues
Level: 1
Multiple Choice:

In a standard breadth-first search (BFS) that uses a queue, when should a newly discovered neighbor be marked as visited to prevent multiple enqueues?

Topic: queues
Level: 1
Fill in the Blank:

In an array-based circular queue, head and tail indices wrap around using _____ arithmetic.

Topic: queues
Level: 2
True or False:

A priority queue removes the highest-priority element before earlier enqueued lower-priority elements.

Topic: queues
Level: 2
Multiple Choice:

In a linked-list implementation of a FIFO queue, which pointers are typically maintained to support O(1) enqueue at the rear and O(1) dequeue at the front?

Topic: queues
Level: 2
Fill in the Blank:

In concurrent systems, a bounded queue helps apply _____ when producers outpace consumers.

Topic: queues
Level: 3
True or False:

In a standard FIFO queue, enqueue adds elements at the rear and dequeue removes elements from the front.

Topic: queues
Level: 3
Multiple Choice:

Which statement about the algorithmic complexity of standard queue operations is correct?

Topic: queues
Level: 3
Fill in the Blank:

In a standard queue interface, the operation that returns the element at the front without removing it is called _____.

Topic: queues
Level: 4
True or False:

In a blocking queue, an enqueue operation may wait until space becomes available when the queue is full.

Topic: queues
Level: 4
Multiple Choice:

In a queue-based system, what is the typical effect of batch dequeuing on throughput and per-item latency?

Topic: queues
Level: 4
Fill in the Blank:

Using a circular buffer for an array-based queue eliminates the need to _____ elements after a dequeue.

Topic: queues
Level: 5
True or False:

In an unweighted graph, a breadth-first search that uses a queue discovers vertices in nondecreasing order of their distance (number of edges) from the start node.

Topic: queues
Level: 5
Multiple Choice:

In a queue implemented with two stacks (in and out), when should elements be transferred from the in stack to the out stack to maintain FIFO order with amortized O(1) operations?

Topic: queues
Level: 5
Fill in the Blank:

Attempting to dequeue from an empty queue typically results in a(n) _____ condition.

Next Topic
used_by
0.97

Breadth First Search
Breadth-first search uses a queue to process vertices in FIFO order, enabling level-order exploration of a graph or tree.
used_by
0.96

Level Order Traversal
Level-order traversal of trees enqueues child nodes to process them in FIFO order, making a queue essential to visit nodes level by level.
used_by
0.95

Breadth-First Search
Breadth-first search uses a FIFO queue to visit nodes level by level in graphs or trees.
used_by
0.94

Breadth-First Search
BFS uses a FIFO queue to process vertices level by level, ensuring nodes are explored in order of discovery.
used_by
0.92

Cpu Scheduling
CPU schedulers maintain ready and waiting queues; algorithms like round-robin and multilevel feedback queue rely on enqueue/dequeue and FIFO behavior to organize process execution.
used_by
0.92

Producer Consumer
The producer-consumer concurrency pattern uses queues to buffer items between producers and consumers, enforcing FIFO order and decoupling production and consumption rates.
used_by
0.9

Message Queues
Message queues apply FIFO queue semantics to deliver messages between processes or services, relying on queue operations for ordering, buffering, and flow control.
used_by
0.9

Event Driven Architecture
Event-driven systems rely on message queues to deliver events asynchronously, buffer spikes, and decouple producers from consumers for scalability, resilience, and backpressure handling.
used_by
0.9

Io Buffering
I/O buffering uses FIFO queues to temporarily hold data between producers (devices or processes) and consumers, smoothing bursty throughput, preserving order, and decoupling differing processing rates.
used_by
0.9

Printer Spooler
A printer spooler uses a FIFO queue to hold and schedule print jobs, enqueuing documents as they are submitted and dequeuing them for printing in order.
used_by
0.88

Topological Sort
Kahn's algorithm for topological sorting uses a FIFO queue to process vertices with zero in-degree, making queues essential to its implementation and correctness.
used_by
0.88

Round Robin Scheduling
Round-robin CPU scheduling maintains a ready queue and cycles through processes in FIFO order, using enqueue/dequeue to allocate time slices fairly.