Queue
easy 15 minA queue is a linear data structure where items join at the rear and leave from the front.
Chapter mnemonic
Which item leaves next?
Lift the top plate. Serve the first guest. Call the urgent case.
The newest arrival has the most urgent case. Which structure serves them first because of urgency?
A priority queue orders removal by priority.
Video lesson · Chapter 1 of 6
The next shopper
The queue in 75 seconds
1:22Reel
How it works
Step through the idea, or press Play.
Enqueue at the rear. A new item always joins the back of the line; nobody cuts in
Understand it
Start here
What a queue is
A queue is a linear data structure where items are added at one end, the rear, and removed from the other end, the front. The first item in is the first item out: FIFO, First In, First Out. Think of a line at a ticket counter: the first person to join is the first to be served.
FIFO order
The oldest item always leaves first.
Two ends, two jobs
Insert only at the rear, remove only at the front.
Order is preserved
Enqueue 1, 2, 3 and you dequeue 1, 2, 3. A stack would reverse it.
The picture
FIFO in one picture
- 1EnqueueJoin at the rear
- 2WaitMove up as others leave
- 3PeekReach the front, be seen
- 4DequeueLeave from the front
Every item walks the same path, so items leave in the order they arrived.
A queue of four, front to rear
The API
Core operations
| Operation | What it does | On 10, 20, 30, 40 |
|---|---|---|
enqueue(x) | Adds x at the rear | enqueue(50) gives 10, 20, 30, 40, 50 |
dequeue() | Removes and returns the front | returns 10, leaves 20, 30, 40 |
peek() / front() | Returns the front without removing it | returns 10, queue unchanged |
is_empty() | True when there is nothing to dequeue | False |
size() | Number of items | 4 |
Under the hood
How enqueue and dequeue work
enqueue(x)
deque or linked list simply grows.dequeue()
peek() follows the same path but stops after reading the value.Complexity
What each operation costs
| Operation | collections.deque | Python list | Why |
|---|---|---|---|
enqueue | amortised | Writes one slot at the rear | |
dequeue | list.pop(0) shifts every remaining item left | ||
peek | Reads the front directly | ||
is_empty, size | The length is tracked as items come and go | ||
| search | Has to walk the line | ||
| the queue itself | space | space | One slot per stored item |
Why list.pop(0) ruins a queue
pop(0) moves everything behind the front. Draining a list-backed queue is quadratic; draining a deque is linear. For BFS that is the difference between and an extra .Implementation
Four ways to build one
collections.deque
appendto enqueue,popleftto dequeue. Blocks of slots linked together, at both ends. The default in Python.Linked list
Keep
head(front) andtail(rear):tail.next = node; tail = node. Never resizes; one pointer per node.Circular array
A fixed buffer where
rear = (rear + 1) % capacitywraps round. Fixed memory, no allocation, can be full.Array plus front index
Append at the end, move a
frontindex instead of shifting, and compact when half the array is dead space.
from collections import dequequeue = deque()queue.append("Alice") # enqueuequeue.append("Bob")queue.append("Carol")print(queue[0]) # peek -> Aliceprint(queue.popleft()) # dequeue -> Aliceprint(len(queue)) # size -> 2print(not queue) # is_empty -> Falseclass Node: def __init__(self, val): self.val = val self.next = Noneclass LinkedQueue: def __init__(self): self.head = self.tail = None # front and rear self.count = 0 def enqueue(self, val): node = Node(val) if self.tail is None: self.head = self.tail = node else: self.tail.next = node # link after the rear self.tail = node self.count += 1 def dequeue(self): if self.head is None: raise IndexError("dequeue from empty queue") val = self.head.val self.head = self.head.next if self.head is None: # queue became empty self.tail = None self.count -= 1 return valq = LinkedQueue()for x in (1, 2, 3): q.enqueue(x)print(q.dequeue(), q.dequeue(), q.count) # 1 2 1Deep dive
The circular buffer
A plain fixed array wastes the slots before the front once items leave. A circular buffer (ring buffer) treats the array as a ring: when the rear reaches the end, it wraps back to slot 0 and reuses freed space. It is modular arithmetic on indexes.
Where the next item goes
Enqueue into a ring of capacity k
count keeps full and empty apart; with only head and tail, both look like head == tail.class CircularQueue: def __init__(self, k): self.buf = [None] * k self.head = 0 self.count = 0 def enqueue(self, x): if self.count == len(self.buf): return False # full self.buf[(self.head + self.count) % len(self.buf)] = x self.count += 1 return True def dequeue(self): if self.count == 0: return None # empty x = self.buf[self.head] self.head = (self.head + 1) % len(self.buf) self.count -= 1 return xcq = CircularQueue(3)print(cq.enqueue(1), cq.enqueue(2), cq.enqueue(3), cq.enqueue(4)) # True True True Falseprint(cq.dequeue()) # 1, frees slot 0print(cq.enqueue(4)) # True: 4 wraps into slot 0print(cq.buf) # [4, 2, 3]Comparison
Queue, stack, deque and priority queue
| Queue | Stack | Deque | Priority queue | |
|---|---|---|---|---|
| Order | FIFO | LIFO | Either end | Smallest (or largest) first |
| Insert | Rear, | Top, | Both ends, | |
| Remove | Front, | Top, | Both ends, | |
| Analogy | Line at a store | Stack of plates | Line open at both ends | Hospital triage |
| Graph traversal | BFS | DFS | 0-1 BFS | Dijkstra |
| Typical use | Scheduling, buffering | Undo, recursion | Sliding window | Top-k, scheduling by urgency |
Use a queue when
- You need first-come, first-served order.
- You do BFS or level-order traversal.
- You schedule tasks or process jobs in arrival order.
- You buffer a data stream between a producer and a consumer.
- You handle asynchronous requests in order.
Do not use a queue when
- You need random access by index (use an array).
- You need LIFO order (use a stack).
- You search for values often (use a set or dict).
- You need priority order (use a priority queue).
- You need both ends equally (use a deque).
Pattern
BFS runs on a queue
The BFS loop
from collections import dequegraph = {"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "E", "F"], "D": ["B"], "E": ["B", "C"], "F": ["C"]}def levels(start): seen, queue, out = {start}, deque([start]), [] while queue: level = [] for _ in range(len(queue)): # exactly the nodes of this level node = queue.popleft() level.append(node) for nb in graph[node]: if nb not in seen: seen.add(nb) # mark on enqueue queue.append(nb) out.append(level) return outprint(levels("A")) # [['A'], ['B', 'C'], ['D', 'E', 'F']]In the wild
Where queues run
Web servers
Incoming HTTP requests wait in a queue until a worker thread is free.
Print spooler
Documents print in the order they were sent.
Message queues
RabbitMQ, Amazon SQS and Kafka topics hand messages from producers to consumers.
BFS
Shortest paths, level-order traversal, flood fill, web crawlers.
Task schedulers
Round-robin CPU scheduling and job runners such as Celery re-queue unfinished work.
Call centres
Callers on hold are answered in the order they called.
Producer and consumer with a queue in between
Pattern spotting
Spotting a queue problem
Should I use a queue?
BFS traversal
Level-by-level exploration of graphs and trees. Process nodes in the order they were discovered.
Multi-source BFS
Enqueue every source first, then run one BFS. Rotting oranges, walls and gates.
Sliding window
A deque gives at both ends; keep it monotonic for window maximum.
Task scheduling
Process in FIFO order and re-enqueue anything unfinished. Round-robin, cooldowns.
Recap
Key takeaways
Key points
- A queue is FIFO: the first item enqueued is the first dequeued, so order is preserved.
- Items join at the rear and leave from the front.
enqueue,dequeue,peek,is_emptyandsizeare ; search is ; space is . - In Python, use
collections.dequewithappendandpopleft.list.pop(0)is . - A circular buffer reuses freed slots with
% capacityand tracks a count to tell full from empty. - BFS is a queue: oldest discovery first gives level order and shortest paths in unweighted graphs.
- Underflow is dequeuing from empty; overflow is enqueuing into a full bounded queue.