Queue in Data Structure — Types & Algorithms (with Examples)
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle: the first element added is the first one removed.
Core Operations
enqueue(item)— insert an element at the rear.dequeue()— remove and return the element at the front.peek()— view the front element without removing it.isEmpty()— check whether the queue has any elements.
Types of Queues
| Type | Description |
|---|---|
| Simple Queue | Basic FIFO queue, insert at rear, remove from front. |
| Circular Queue | Rear wraps back to the front to reuse freed space. |
| Priority Queue | Elements are served according to priority, not order of arrival. |
| Deque | Insertion and removal allowed at both ends. |
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.popleft()
def peek(self):
return self.items[0]
def is_empty(self):
return len(self.items) == 0
Complexity
| Operation | Time |
|---|---|
| Enqueue | O(1) |
| Dequeue | O(1) |
| Peek | O(1) |
Applications
- Task and process scheduling in operating systems.
- Breadth First Search traversal in graphs.
- Handling of asynchronous data such as I/O buffers and print queues.
Building a Circular Queue on a Fixed Array
A simple array-based queue wastes space: once items are dequeued from the front, those slots are never reused. A circular queue fixes this by letting the front and rear indexes wrap around using the modulo operator.
class CircularQueue:
def __init__(self, capacity):
self.data = [None] * capacity
self.capacity = capacity
self.front = 0
self.size = 0
def enqueue(self, item):
if self.size == self.capacity:
raise OverflowError("queue is full")
rear = (self.front + self.size) % self.capacity
self.data[rear] = item
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError("queue is empty")
item = self.data[self.front]
self.data[self.front] = None
self.front = (self.front + 1) % self.capacity
self.size -= 1
return item
Tracking size separately avoids the classic ambiguity where front equals rear could mean either "empty" or "full". Trying to add to a full queue is called overflow; removing from an empty one is underflow. Both should be handled explicitly rather than left to crash.
Priority Queues with a Heap
A priority queue does not serve items in arrival order, so a plain list is a poor fit. A binary heap keeps the smallest (or largest) priority at the top, giving O(log n) insertion and removal. Python's heapq module provides a min-heap:
import heapq
tasks = []
heapq.heappush(tasks, (2, "send report"))
heapq.heappush(tasks, (1, "fix outage"))
heapq.heappush(tasks, (3, "update docs"))
while tasks:
priority, name = heapq.heappop(tasks)
print(priority, name) # 1 fix outage, 2 send report, 3 update docs
For highest-first ordering, store negative priorities. If two items can share a priority and the payload cannot be compared, add an increasing counter as a tie-breaker in the tuple.
Queue in a Real Algorithm: Breadth First Search
BFS explores a graph level by level, and the queue is what guarantees that order. Nodes discovered first are processed first, so all neighbours at distance one are visited before any node at distance two.
from collections import deque
def bfs(graph, start):
visited = {start}
order = []
q = deque([start])
while q:
node = q.popleft()
order.append(node)
for nxt in graph[node]:
if nxt not in visited:
visited.add(nxt)
q.append(nxt)
return order
Marking a node as visited when it is enqueued, not when it is dequeued, stops the same node from entering the queue several times.
Picking the Right Queue and Avoiding Traps
- Stack or queue? Use a stack (LIFO) for undo, backtracking and depth-first work; use a queue (FIFO) when fairness or level order matters.
- Do not use
list.pop(0)as a queue in Python. Each call shifts every remaining element, making dequeue O(n).collections.dequegives O(1) at both ends. - Thread safety. When several threads produce and consume work, use
queue.Queue, which handles locking and lets consumers block until an item arrives. - Deque for sliding windows. Problems like "maximum in every window of size k" become linear time with a deque that drops indexes from both ends.
Quick check before coding: decide the serving order, decide whether size is bounded, and decide what should happen on overflow and underflow.