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
| Application | Why a queue fits |
|---|---|
| CPU and process scheduling | Processes 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 spooling | Print jobs are served in arrival order |
| Message queues between services | A producer adds messages and a consumer processes them later, at its own pace |
| Web server request handling | Incoming requests wait for a free worker, in order |
| Buffers for streaming and I/O | Data is read in the order it was written |
| Customer support and ticketing | First come, first served, often with priorities |
| Level-order tree traversal | Visit all nodes of one level before the next |
| Caches with FIFO eviction | The oldest entry is removed first |
Application 1: breadth-first search
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
| Type | How it differs | Used for |
|---|---|---|
| Simple queue | Strict FIFO | Print jobs, request lines |
| Circular queue | The end wraps around to the start of a fixed array, reusing freed space | Fixed-size buffers, traffic-light cycles, streaming |
| Priority queue | Items leave by priority, not arrival; usually a heap | Task schedulers, Dijkstra's algorithm, emergency triage |
| Deque (double-ended queue) | Add and remove at both ends | Sliding-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
| Operation | Time |
|---|---|
| Enqueue | O(1) |
| Dequeue | O(1) with a deque or linked list |
| Peek at the front | O(1) |
| Search for an item | O(n) |
| Priority queue push and pop | O(log n) |
Queue vs stack
| Queue | Stack | |
|---|---|---|
| Order | First in, first out | Last in, first out |
| Main operations | enqueue, dequeue | push, pop |
| Used for | Scheduling, BFS, buffering | Undo, function calls, depth-first search, expression parsing |
Practice problems, in order
- Implement Queue using Stacks
- Number of Recent Calls
- Design Circular Queue
- Binary Tree Level Order Traversal
- Rotting Oranges
- 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.


