3 / 7 · Intermediate
Queues
Taking the first of 1,000 values out of a JavaScript array with shift moves the other 999; a ring buffer does the same job in one step.
Jump to the 10 practice questions1Explore
First in, first out
A queue is a line at a shop counter. People join at the back and are served from the front, so whoever arrived first leaves first. The rule is first in, first out (FIFO). The two operations are enqueue, which adds a value at the back, and dequeue, which removes the value at the front. In MIT's 6.006 notes a queue is the sequence interface limited to insert last(x) and delete first().
enqueue joins at the back, dequeue takes from the front. Watch the step count of each dequeue.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
2Problem
The order out
A queue gives back values in which order?
Hint
A line at a counter.
Solution
Answer: First in, first out
Like a line at a counter: the first to join is the first served (FIFO).
3Problem
A, B, C, then D
Enqueue A, B, C. Dequeue once. Enqueue D. Now dequeue until empty. Put those values in order.
- D
- C
- B
Hint
A leaves first; D joins behind C.
Solution
Answer:
- B
- C
- D
A left first. The line is then B, C, D, and they leave in that order.
4Explain
Where queues are used
Queues are everywhere that work must be handled in arrival order: documents waiting for a printer, key presses waiting for a program, messages waiting for a server. Breadth-first search, from the algorithms course, keeps the squares it still has to visit in a queue, and that is exactly why it explores in rings of equal distance.
5Problem
A search with a queue
Which search from the algorithms course keeps its waiting squares in a queue?
Hint
It explores in rings of equal distance.
Solution
Answer: Breadth-first search
BFS takes squares out in the order they were found, which makes it go ring by ring.
6Explore
push and shift
In JavaScript the obvious queue is an array: push to enqueue at the back and shift to dequeue from the front. It works, and for short queues it is fine. But look at what shift does. MDN says it "shifts all values to the left by 1", and the ECMAScript specification writes it as a loop that copies element k to position k − 1 for every k. The front of an array is the expensive end, as the first unit showed. Dequeuing from a queue of n values costs 1 read plus n − 1 moves, so a queue of 1,000 values costs 1,000 steps per dequeue.
Enqueue all five, then dequeue all five. The total ends at 20: most of it is moving values that stay in the queue.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
7Problem
One dequeue from 4 values
With push and shift, how many steps does one dequeue take on a queue of 4 values (1 read plus moves)?
Hint
1 read, then 3 moves.
Solution
Answer: 4
Read the front, then move the other 3 values left: 1 + 3 = 4.
8Problem
Five in, five out
Start with an empty array. Enqueue 5 values with push, then dequeue all 5 with shift. How many steps in total?
Hint
5 + (5 + 4 + 3 + 2 + 1).
Solution
Answer: 20
Enqueues: 5 × 1 = 5. Dequeues on 5, 4, 3, 2, 1 values: 5 + 4 + 3 + 2 + 1 = 15. Total 20.
9Problem
A thousand waiting
Same method, a queue of 1,000 values: how many steps for one dequeue?
Hint
1 read + 999 moves.
Solution
Answer: 1000
1 read + 999 moves = 1,000. The cost grows with the length of the queue.
10Explore
A head index
The fix is to stop moving values and instead remember where the front is. Keep an index called head. Dequeue reads the value at head and adds 1 to head; nothing else moves. The catch is that the cells before head are wasted. A ring buffer (circular buffer) reuses them: the array has a fixed number of cells, say 8, and positions wrap round, so the cell after 7 is 0.
Dequeue reads the value at head and moves head on. Nothing moves, but the faded cells before head are wasted.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
11Explore
A ring buffer
Try this in the lab: switch to the ring buffer, enqueue four times to fill all 8 cells, and enqueue once more. The lab refuses, because a fixed ring has no ninth cell. Then dequeue twice and enqueue again: the new value goes into cell 0, wrapping round.
Eight cells. Fill them, try one more enqueue, then dequeue twice and enqueue again: the new value wraps round into cell 0.
Press a button: each one runs one operation and shows what it cost.
[1,2,3,4]Total steps 0
12Problem
Where the next value goes
A ring buffer has 8 cells (0 to 7), head = 6 and size = 3. Which cell does the next enqueue use?
Hint
(6 + 3) mod 8.
Solution
Answer: 1
(head + size) mod 8 = (6 + 3) mod 8 = 9 mod 8 = 1. The position wraps round.
13Problem
A full ring
A fixed ring of 8 cells holds 8 values. What happens on enqueue?
Hint
There is no ninth cell.
Solution
Answer: The queue is full and the value is refused
A fixed ring has no free cell; it must refuse (or be copied into a bigger ring).
14Problem
Dequeue from a ring
How many steps does a dequeue from a ring buffer take, however many values it holds?
Hint
Only head changes.
Solution
Answer: 1
Take the value at head and move head on by one; no value moves.
15Explain
Which one to use
Which one should you use? For a queue that never holds more than a few dozen values, push and shift is short and clear, and the moving costs almost nothing. For a queue that thousands of items pass through, such as the squares of a large breadth-first search, a head index or a ring buffer keeps every dequeue at one step.
| Queue on n values | Enqueue | Dequeue |
|---|---|---|
| Array with push and shift | 1 (amortized) | 1 read + (n − 1) moves |
| Array with a head index | 1 (amortized) | 1, but front cells are wasted |
| Ring buffer of fixed size | 1, or full | 1 |
16Problem
Two sequence operations
In MIT 6.006 terms, a queue uses which two sequence operations?
Hint
Join at the back, leave from the front.
Solution
Answer: insert last and delete first
Join at the back (insert last), leave from the front (delete first).
17Practice
Dequeue with a head index
Write dequeue with a head index. The program should print A, B, C and then 1, the number of values still waiting (only D).
A
B
C
1const q = { items: [], head: 0 };
function enqueue(q, v) { q.items.push(v); }
function dequeue(q) {
// Return q.items[q.head] and add 1 to q.head. Do not use shift.
return undefined;
}
enqueue(q, "A"); enqueue(q, "B"); enqueue(q, "C");
console.log(dequeue(q));
console.log(dequeue(q));
enqueue(q, "D");
console.log(dequeue(q));
console.log(q.items.length - q.head);
Hint
Read the value at head first, then move head on.
A solution
const q = { items: [], head: 0 };
function enqueue(q, v) { q.items.push(v); }
function dequeue(q) {
const v = q.items[q.head];
q.head++;
return v;
}
enqueue(q, "A"); enqueue(q, "B"); enqueue(q, "C");
console.log(dequeue(q));
console.log(dequeue(q));
enqueue(q, "D");
console.log(dequeue(q));
console.log(q.items.length - q.head);18Practice
Enqueue into a ring
Finish enqueue for a ring of 4 cells. It should print 1 2, then 5 6 3 4 (5 and 6 wrapped round into cells 0 and 1), then 3 4 5 6.
1 2
5 6 3 4
3 4 5 6const N = 4;
const buf = new Array(N).fill(null);
let head = 0, size = 0;
function enqueue(v) {
if (size === N) return false;
// Put v into buf[(head + size) % N], then add 1 to size.
return true;
}
function dequeue() {
if (size === 0) return null;
const v = buf[head];
head = (head + 1) % N;
size--;
return v;
}
for (const v of [1, 2, 3, 4]) enqueue(v);
console.log(dequeue(), dequeue());
enqueue(5); enqueue(6);
console.log(buf.join(" "));
console.log(dequeue(), dequeue(), dequeue(), dequeue());
Hint
The back of the queue is head + size, wrapped round with % N.
A solution
const N = 4;
const buf = new Array(N).fill(null);
let head = 0, size = 0;
function enqueue(v) {
if (size === N) return false;
buf[(head + size) % N] = v;
size++;
return true;
}
function dequeue() {
if (size === 0) return null;
const v = buf[head];
head = (head + 1) % N;
size--;
return v;
}
for (const v of [1, 2, 3, 4]) enqueue(v);
console.log(dequeue(), dequeue());
enqueue(5); enqueue(6);
console.log(buf.join(" "));
console.log(dequeue(), dequeue(), dequeue(), dequeue());19Explain
Common mistakes
const queue = ["A", "B", "C"];
console.log(queue.pop());Cconst queue = ["A", "B", "C"];
console.log(queue.shift());Apop takes from the back, which turns the queue into a stack. A dequeue takes the front.
20
Summary
- A queue is first in, first out: enqueue at the back, dequeue from the front.
- shift moves every remaining value, so dequeuing from n values costs n steps.
- A head index or a ring buffer makes dequeue 1 step.
- In a ring of size c, the next free cell is (head + size) mod c.