Queues
Queues
A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. Think of people waiting in line — the first person who arrives is the first person served. Elements are added at the back (enqueue) and removed from the front (dequeue). This ordering makes queues fundamental to scheduling, buffering, and breadth-first traversal.
Core Operations
| Operation | Description | Time Complexity |
|---|---|---|
enqueue(item) | Add an element to the back | O(1) |
dequeue() | Remove and return the front element | O(1) |
peek() / front() | View the front element without removing it | O(1) |
is_empty() | Check if the queue is empty | O(1) |
size() | Return the number of elements | O(1) |
How It Works
- Enqueue: Add a new element to the rear of the queue. Advance the rear pointer.
- Dequeue: Remove the element at the front. Advance the front pointer. Return the removed element.
- Peek: Read the front element without modifying the queue.
A queue maintains two pointers — one for the front (where elements leave) and one for the rear (where elements enter).
Step-by-Step Example
Starting with an empty queue:
enqueue(10) → Queue: [10] (front=10, rear=10)
enqueue(20) → Queue: [10, 20] (front=10, rear=20)
enqueue(30) → Queue: [10, 20, 30] (front=10, rear=30)
dequeue() → Returns 10, Queue: [20, 30] (front=20, rear=30)
peek() → Returns 20, Queue: [20, 30] (unchanged)
dequeue() → Returns 20, Queue: [30] (front=30, rear=30)
Code Snippet
class Queue:
"""Queue implementation using a list with front pointer for O(1) operations."""
def __init__(self):
self._items = []
self._front = 0
def enqueue(self, item) -> None:
"""Add an element to the back of the queue."""
self._items.append(item)
def dequeue(self):
"""Remove and return the front element. Raises error if empty."""
if self.is_empty():
raise IndexError("Dequeue from empty queue")
item = self._items[self._front]
self._front += 1
# Reclaim memory when half the list is unused
if self._front > len(self._items) // 2:
self._items = self._items[self._front:]
self._front = 0
return item
def peek(self):
"""Return the front element without removing it."""
if self.is_empty():
raise IndexError("Peek at empty queue")
return self._items[self._front]
def is_empty(self) -> bool:
"""Check if the queue has no elements."""
return self._front >= len(self._items)
def size(self) -> int:
"""Return the number of elements in the queue."""
return len(self._items) - self._front
Circular Queue (Fixed-Size)
A circular queue uses a fixed-size array and wraps around when reaching the end. This avoids wasted space:
class CircularQueue:
"""Fixed-size queue using circular array indexing."""
def __init__(self, capacity: int):
self._items = [None] * capacity
self._capacity = capacity
self._front = 0
self._rear = 0
self._size = 0
def enqueue(self, item) -> bool:
"""Add element. Returns False if full."""
if self._size == self._capacity:
return False
self._items[self._rear] = item
self._rear = (self._rear + 1) % self._capacity
self._size += 1
return True
def dequeue(self):
"""Remove and return front element."""
if self._size == 0:
raise IndexError("Dequeue from empty queue")
item = self._items[self._front]
self._front = (self._front + 1) % self._capacity
self._size -= 1
return item
def is_empty(self) -> bool:
return self._size == 0
def is_full(self) -> bool:
return self._size == self._capacity
Complexity Analysis
Time Complexity: O(1) per operation
Every queue operation (enqueue, dequeue, peek) takes constant time. There's no traversal — you always work with the front or rear pointer directly.
Space Complexity: O(n)
The queue uses space proportional to the number of elements currently stored.
Queue Variants
| Variant | Description |
|---|---|
| Simple Queue | Basic FIFO — enqueue at rear, dequeue from front |
| Circular Queue | Fixed-size with wrap-around indexing |
| Double-ended Queue (Deque) | Add/remove from both ends |
| Priority Queue | Dequeue returns highest-priority element (uses heap) |
When to Use Queues
- Breadth-First Search (BFS): Queues power level-by-level graph/tree traversal.
- Task scheduling: Operating systems use queues to schedule CPU processes (round-robin).
- Message buffering: Message queues (RabbitMQ, SQS) buffer work between producers and consumers.
- Print spooling: Documents queue up and print in the order submitted.
- Rate limiting: Sliding window rate limiters use queues to track request timestamps.
- Stream processing: Data pipelines buffer events in queues between processing stages.
Stack vs. Queue
| Property | Stack (LIFO) | Queue (FIFO) |
|---|---|---|
| Add to | Top | Back |
| Remove from | Top | Front |
| Traversal style | Depth-first | Breadth-first |
| Real-world analogy | Stack of plates | Line at a store |
Key Properties
| Property | Value |
|---|---|
| Access pattern | FIFO (First-In, First-Out) |
| Enqueue/Dequeue | O(1) |
| Random access | Not supported |
| Variants | Circular, Deque, Priority |