Skip to content
Explainer ยท Data Structures and Algorithms

Applications of Queue in Data Structure: Real-World Uses, Types and Code Examples

By Younus FardeenUpdated 4 Nov 20264 min read
Short answer

A queue is a first-in, first-out (FIFO) structure, so it is used wherever items must be handled in the order they arrive. Its main applications are CPU and task scheduling, breadth-first search, printer and request buffering, message queues between services, handling streaming data, and level-order tree traversal. Variants such as the priority queue, circular queue and deque cover urgent tasks, fixed buffers and sliding windows.

A queue models a line at a ticket counter: the person who joined first is served first. That one rule explains almost every use below.

What a queue is

A queue supports two main operations: enqueue adds an item at the back, and dequeue removes the item at the front. Python's collections.deque gives both in O(1) time.

from collections import deque

queue = deque()
queue.append("order 1")        # enqueue at the back
queue.append("order 2")
queue.append("order 3")
print(queue.popleft())         # dequeue from the front: first in, first out
print(list(queue))

Output: order 1 then ['order 2', 'order 3']

Avoid list.pop(0) for queues: it shifts every element, which is O(n).

Main applications of a queue

ApplicationWhy a queue fits
CPU and process schedulingProcesses wait in a ready queue and get the processor in turn (round robin)
Breadth-first search (BFS)Visit a node's neighbours before going deeper, in the order found
Printer and job spoolingPrint jobs are served in arrival order
Message queues between servicesA producer adds messages and a consumer processes them later, at its own pace
Web server request handlingIncoming requests wait for a free worker, in order
Buffers for streaming and I/OData is read in the order it was written
Customer support and ticketingFirst come, first served, often with priorities
Level-order tree traversalVisit all nodes of one level before the next
Caches with FIFO evictionThe oldest entry is removed first

BFS finds the shortest path in an unweighted graph by exploring nodes layer by layer. The queue keeps the order.

from collections import deque

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}

def bfs(start):
    visited, order, queue = {start}, [], deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbour in graph[node]:
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(neighbour)
    return order

print(bfs("A"))

Output: ['A', 'B', 'C', 'D', 'E', 'F']

Application 2: CPU scheduling with round robin

Each job runs for a fixed time slice, then goes to the back of the queue if it is not finished.

from collections import deque

jobs = deque([("P1", 5), ("P2", 3), ("P3", 7)])   # (name, time still needed)
quantum, clock = 3, 0
while jobs:
    name, remaining = jobs.popleft()
    run = min(quantum, remaining)
    clock += run
    if remaining - run > 0:
        jobs.append((name, remaining - run))      # not finished: back of the queue
    else:
        print(f"{name} finished at t={clock}")

Output: P2 finished at t=6, P1 finished at t=11, P3 finished at t=15

Types of queues and where each is used

TypeHow it differsUsed for
Simple queueStrict FIFOPrint jobs, request lines
Circular queueThe end wraps around to the start of a fixed array, reusing freed spaceFixed-size buffers, traffic-light cycles, streaming
Priority queueItems leave by priority, not arrival; usually a heapTask schedulers, Dijkstra's algorithm, emergency triage
Deque (double-ended queue)Add and remove at both endsSliding-window problems, undo and redo, palindrome checks

Priority queue example

import heapq

tasks = []
heapq.heappush(tasks, (2, "send report"))
heapq.heappush(tasks, (1, "fix login bug"))     # lower number = higher priority
heapq.heappush(tasks, (3, "update docs"))
while tasks:
    priority, task = heapq.heappop(tasks)
    print(priority, task)

Output: 1 fix login bug, 2 send report, 3 update docs

Deque example: sliding window maximum

A deque keeps candidates in decreasing order, so the maximum of every window is at the front.

function slidingMax(nums, k) {
  const deque = [];                 // stores indexes; values stay in decreasing order
  const result = [];
  for (let i = 0; i < nums.length; i++) {
    while (deque.length && deque[0] <= i - k) deque.shift();           // out of the window
    while (deque.length && nums[deque[deque.length - 1]] < nums[i]) deque.pop();
    deque.push(i);
    if (i >= k - 1) result.push(nums[deque[0]]);
  }
  return result;
}

console.log(slidingMax([1, 3, -1, -3, 5, 3, 6, 7], 3));

Output: [ 3, 3, 5, 5, 6, 7 ]

Complexity

OperationTime
EnqueueO(1)
DequeueO(1) with a deque or linked list
Peek at the frontO(1)
Search for an itemO(n)
Priority queue push and popO(log n)

Queue vs stack

QueueStack
OrderFirst in, first outLast in, first out
Main operationsenqueue, dequeuepush, pop
Used forScheduling, BFS, bufferingUndo, function calls, depth-first search, expression parsing

Practice problems, in order

  1. Implement Queue using Stacks
  2. Number of Recent Calls
  3. Design Circular Queue
  4. Binary Tree Level Order Traversal
  5. Rotting Oranges
  6. Sliding Window Maximum

For more explanation, read the Masai guide to the applications of queue, and see the applications of array next.

Frequently asked questions

What are the applications of a queue?

CPU and task scheduling, breadth-first search, printer spooling, message queues, request buffering, streaming data, level-order traversal and FIFO caches.

What are real-life examples of a queue?

A line at a ticket counter, cars at a toll booth, print jobs waiting for a printer and customers waiting for support are all queues.

What is the difference between a queue and a priority queue?

A queue serves items in arrival order. A priority queue serves the item with the highest priority first, whatever its arrival time.

Why is a queue used in BFS?

BFS must explore nodes in the order they were discovered, layer by layer. A FIFO queue gives exactly that order.

How is a queue implemented?

With a linked list, a circular array or a deque. Use a structure with O(1) removal from the front, not a plain array that shifts elements.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Learning path

Data Structures and Algorithms learning path

Arrays to dynamic programming in order, with a problem plan.

Explainer

Applications of array

Where arrays are used and the patterns that solve array problems.

Open →
Explainer

HashMap explained

How hashing, buckets and collisions work, with Python, JS and Java.

Open →