Add at the back and remove from the front, see a queue on a ring buffer and on a linked list, work at both ends with a deque, and build your own ring buffer.
You are building the matching service of a ride-hailing app. Riders send requests faster than drivers become free. When a driver is free, the service must give them the rider who has waited longest.
Nobody wants the newest request first, and nobody wants one from the middle. The oldest request that is still waiting must go first.
Any array or list could hold the requests. What matters is the rule for using it: add at one end, and remove from the other. That rule is called a queue.
Think of the line at a railway ticket counter. A new person joins at the back. The clerk serves the person at the front. Nobody pushes into the middle, and nobody leaves from the back.
The person who arrived first is served first. In a queue, the people are values, and the two ends are the only places where anything happens.
A ticket counter: new people join at the back, and the clerk serves the front. The first in the line is the first served.
A queue is a rule about how you use storage. It is not a new kind of memory. It can sit on a linked list: a head pointer marks the front and a tail pointer marks the back.
Or it can sit on an array used as a ring. The values lie in cells, a head index marks the front, and a tail index marks the next free cell.
Step through the picture below. Watch what moves when you add and remove, and what never moves.
Step by step: A queue on a ring and on a linked list. The animated player loads in your browser.
So a queue is a collection where you add at the back and remove from the front. Six words appear in every queue problem:
Predict what happens
Q You enqueue 4, then 9, then 2 onto an empty queue. Then you dequeue once. Which value comes out?
Answer: A
A queue is first in, first out. The value 4 has waited longest, so it is at the front and dequeue returns it. The value 2 stays at the back until every value in front of it has left.
Every queue operation works at an end. That is the whole design. Nothing in the middle is touched, so the cost does not depend on how long the queue is.
We count the work in steps. A step is a cell written, a pointer changed, a value copied or a node looked at.
An array has a fixed size, and a queue keeps moving forward. Enqueue at the back and dequeue at the front, and the used cells slide along the block until they reach its end. The fix is to treat the block as a ring: after the last cell comes cell 0.
Two indexes do the work. The head is the cell that holds the front value. The tail is the next free cell, where the next value goes. To move either one on, add 1 and take the remainder after dividing by the number of cells.
Enqueue writes the value at the tail, then moves the tail on. Dequeue hands back the value at the head, then moves the head on. Nothing is ever shifted, because only two numbers change.
Exercise · Find the bug: The queue that reads out of order. This function lists a ring buffer's values from the front to the back. It is right until the values wrap round the end of the block. Which line is wrong?
def queue_order(cells, head, count):
result = []
for i in range(count):
result.append(cells[(head + i) % count])
return resultA ring buffer: the head and the tail move on by one cell, and wrap round to cell zero after the last cell. Nothing is shifted.
Step by step: Enqueue 25 onto a ring buffer. The animated player loads in your browser.
Step by step: The tail wraps round to cell 0. The animated player loads in your browser.
Predict what happens
Q A ring has 4 cells, numbered 0 to 3. The tail is at cell 3. You enqueue one value. Where is the tail afterwards?
Answer: B
The ring has no cell 4. The remainder operator wraps the tail to cell 0. The value is written into cell 3 first, and then the tail moves on.
Exercise · Predict the output: Where do head and tail stop?. A ring has 4 cells. A positive number enqueues that value, and 0 dequeues. After these operations, what do head, tail and count print?
cells = [0] * 4
head = tail = count = 0
for op in [7, 8, 9, 0, 0, 5, 6]:
if op > 0:
cells[tail] = op
tail = (tail + 1) % 4
count += 1
else:
head = (head + 1) % 4
count -= 1
print(head, tail, count)What if every cell is in use? Then the head and the tail point at the same cell, and the ring is full. An empty ring looks the same: both indexes meet. So a ring buffer also keeps a count of its values, or leaves one cell empty, to tell the two states apart.
Exercise · Break it: Find the ring that looks empty. This function replays enqueues (a positive number) and dequeues (0) on a ring of cap cells, and returns how many values are in it from the head and tail alone. Find an input where it gives the wrong answer.
def ring_size(cap, ops):
head = tail = 0
for op in ops:
if op > 0:
tail = (tail + 1) % cap
else:
head = (head + 1) % cap
return (tail - head + cap) % capA ring that must hold more values cannot grow in place. It makes a new block twice as big and copies the values across in queue order, front first. That copy also straightens out any wrap-around.
The enqueue that finds the ring full pays one step for each value copied, so it is the slow one. It is rare, and the average enqueue is still O(1).
Exercise · Put it in order: Grow the ring. Arrange the lines into a function that moves a ring's values into a block twice as big. The values must end up in queue order from cell 0, and the rest of the block stays 0.
def grow(cells, head, count):
size = len(cells)
bigger = [0] * (2 * size)
for i in range(count):
bigger[i] = cells[(head + i) % size]
return bigger
bigger = [0] * size
bigger[i] = cells[i]A full ring grows by copying every value, in queue order, into a block twice as big. That enqueue is slow, but rare.
Step by step: Enqueue 8 onto a full ring. The animated player loads in your browser.
Predict what happens
Q A ring with 8 cells holds 8 values. The next enqueue copies them to a block of 16 cells and writes the new value. How many steps is that enqueue?
Answer: C
The copy touches each of the 8 old values once, and the write touches one cell. The empty cells in the new block cost nothing until they are used.
On a linked list, the head is the front and the tail is the back. To enqueue, make a node, point the old tail's next at it, and move the tail. To dequeue, move the head to the next node and hand back the old one. Each takes a constant number of pointer changes.
There is one trap. When the last node leaves, the tail must become null as well. Forget it, and the tail points at a node that is no longer in the queue.
Step by step: Enqueue 25 onto a linked queue. The animated player loads in your browser.
Dequeue removes the front value. In a ring the head moves on by one cell. In a list the head moves to the next node.
Peek reads the front and changes nothing. Both need a front to exist, so check that the queue is not empty first.
Step by step: Dequeue the front of a queue. The animated player loads in your browser.
Predict what happens
Q A queue holds 6, 1, 8 from front to back. You run enqueue 5, then dequeue, then dequeue. What is at the front now?
Answer: A
Enqueue 5 gives 6, 1, 8, 5. The two dequeues remove 6 and then 1. That leaves 8, 5, with 8 at the front.
A deque (say "deck") is a queue that works at both ends. You can push at the front or the back, and pop from the front or the back. It is also called a double-ended queue. A plain queue is a deque that only uses two of the four moves.
A ring handles all four in one step: the tail moves forward or back, and so does the head. A linked list needs care. Pushing at the front is easy.
But popping from the back needs the node before the tail. A singly linked list can only find it by walking from the head. A doubly linked list keeps a prev link in every node, so the tail steps back in one move.
A deque works at both ends. On a doubly linked list, pushing at the front and popping from the back each take a few pointer changes.
Step by step: A deque on a doubly linked list. The animated player loads in your browser.
Step by step: Pop back on a singly linked list. The animated player loads in your browser.
A deque can also keep a window's largest value ready. Take a stream of numbers and a window of 3. You want the maximum of every window as it slides along. Checking every window costs about n times 3 steps.
Instead, keep a deque of positions, with the biggest value at the front and smaller values behind it. When a new value arrives, remove every smaller value from the back. They can never be the maximum while the new value is in the window.
Then add the new position at the back. If the front has slid out of the window, remove it from the front. The front is the answer.
Every value goes on once and comes off at most once, so the whole run costs O(n).
A monotonic deque keeps the positions of a window's big values, going down from the front. The front is always the maximum.
Step by step: The maximum of every window of 3. The animated player loads in your browser.
Here is every operation side by side. The ring column has one footnote: an enqueue that finds the ring full costs O(n). The last two rows show where a queue is weak.
| Operation | Ring buffer | Singly linked list | Doubly linked list | What sets the cost |
|---|---|---|---|---|
| Enqueue (add at the back) | O(1) on average; O(n) for the one add that grows a full ring | O(1): a new node and two pointer changes | O(1): three pointer changes | Only the back is touched |
| Dequeue (remove at the front) | O(1): the head moves on one cell | O(1): the head moves to the next node | O(1) | Only the front is touched |
| Peek (read the front) | O(1) | O(1) | O(1) | One read |
| Push front, a deque move | O(1): the head steps back one cell | O(1) | O(1) | The front is one pointer away |
| Pop back, the other end of a deque | O(1): the tail steps back one cell | O(n): walk from the head to find the node before the tail | O(1): follow prev | Whether a link leads backwards |
| Search for a value | O(n): look from the front | O(n) | O(n) | A queue has no index and no order to use |
| Memory for each value | One cell, plus spare room | One node: the value and a pointer | One node: the value and two pointers | The list pays for pointers |
The ring is the fastest in practice, because its values sit side by side. A list never has to grow a block and copy it, but each node costs more memory. For a deque, choose a ring or a doubly linked list.
Now drive the queue yourself. Type a value, then use the queue buttons or the deque buttons, and watch each operation run step by step. The step counter shows the cost. The panel below it shows what the same operation costs when the queue is stored the other way.
Try these six, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a RingQueue class with a block of 4 cells, a head index and a count. You write five methods: enqueue, dequeue, front, size and is_empty. The sixth, to_list, is already written, so the tests can look inside your queue.
The part to take care over is the wrap and the growth. The tests enqueue and dequeue enough values to wrap the tail round the block. They also enqueue more than 4 values at once.
When the block is full, make a new block twice as big. Copy the values across in queue order, starting at cell 0, and set head back to 0.
Each test creates a new, empty queue, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Three rules keep the queue correct after every method:
head. The next free cell is (head + count) mod capacity.dequeue reads the front value first, then moves head on and lowers count.-1 from dequeue and front, and never crashes.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a queue when work must be done in the order it arrived. A print queue, a line of ride requests and a worker that handles jobs one by one all work this way. A message queue between two services does the same job at a larger scale.
Queues also drive breadth-first search: visit a node, add its neighbours at the back, and take the next node from the front. And a deque fits a sliding window, where values enter at one end and leave at the other.
Choose a stack when the newest item must go first, as in undo. Choose an array when you read by index. Choose a priority queue (a heap) when the most urgent item must go first, even if it arrived last. Choose a hash map when you look values up by key.
A queue gives you the oldest item and nothing else. Every other item is out of reach until the ones in front of it have left.
items.pop(0) and items.insert(0, x) work as dequeue and enqueue, but each call shifts every other value by one cell. A loop of n dequeues then costs about n^2 / 2 shifts. Use collections.deque and queue.popleft(), or keep a head index and never shift.
The classic mistake: taking from the front of a Python list with pop at zero. Every other value slides one place, so each dequeue costs the whole length.
self.tail = self.tail + 1 has no wrap, so the tail walks off the end of the block. And % (capacity - 1) skips the last cell. Write self.tail = (self.tail + 1) % len(self.cells), and test a queue that has wrapped more than once.
In a ring buffer, if self.head == self.tail: is true when the ring is empty and also when it is full. A code that treats both as empty drops the whole queue on the next dequeue. Keep a count, and test if self.count == 0: and if self.count == len(self.cells):.
while True: queue.append(job) never stops if producers are faster than consumers. The queue grows until the machine runs out of memory. Give a queue a maximum size, and decide what happens when it is full: wait, drop the newest, or tell the producer to slow down.
In a linked queue, head = head.next is not enough when the list had one node. The head becomes null, but tail still points at the removed node. The next enqueue then links a new node to a node that is no longer in the queue, and the new value is lost. When the head becomes null, set the tail to null too.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The idea
Q You enqueue 5, 2, 8 and 1 onto an empty queue, then dequeue twice. What is at the front now?
Answer: C
Enqueuing gives 5, 2, 8, 1 with 5 at the front. The first dequeue removes 5 and the second removes 2. That leaves 8, 1, with 8 at the front.
Checkpoint · Costs and the ring
Q1/4 How many steps does a dequeue take on a ring buffer holding 1,000,000 values?
Answer: A
Dequeue only moves the head. No value is copied or shifted, so the length does not matter.
Q2/4 A ring has 5 cells, numbered 0 to 4, and the head is at cell 4. You dequeue one value. Where is the head afterwards?
Answer: B
The ring has no cell 5. The head wraps round to cell 0. That is how the block is reused without shifting any value.
Q3/4 In a ring buffer the head and the tail point at the same cell. What does that tell you?
Answer: C
An empty ring and a full ring look the same from the two indexes alone. A count, or one cell kept empty on purpose, tells them apart.
Q4/4 An enqueue finds a full ring of 4 cells. It makes a block of 8 cells and copies the 4 values across. How many steps is that enqueue?
Answer: C
The 4 old values are each copied once, then the new value is written. The 4 spare cells in the new block cost nothing until they are used.
Checkpoint · The deque
Q1/3 You need to remove the last node of a singly linked queue with a tail pointer. What does it cost?
Answer: B
The tail points at the last node, but nothing points back from it. Only a walk from the head finds the node before it. A doubly linked list keeps a prev link, so the same removal is O(1).
Q2/3 In the sliding-window maximum, a new value arrives and the back of the deque holds a smaller value. What happens to the smaller one?
Answer: B
The new value is bigger and arrived later, so it stays in the window longer. The smaller value can never be the maximum while the new one is there, so it is removed.
Q3/3 Why is the sliding-window maximum with a monotonic deque O(n), not O(n times k)?
Answer: B
Each value is pushed once and popped at most once, so the total work is at most 2n deque steps, however big the window is.
Checkpoint · Mistakes and choices
Q1/2 A loop runs while items: current = items.pop(0) on a Python list of 100,000 values. What is the problem?
Answer: B
Removing the first element of an array shifts every later element one place. Use collections.deque with popleft(), or keep a head index.
Q2/2 Which job is the best fit for a queue?
Answer: B
Ride requests must be served oldest first, which is first in, first out. Undo needs a stack, a position needs an array, and a lookup by id needs a hash map.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.