1 / 7 · Intermediate
Arrays
Reading the millionth value of an array takes one step, but putting a new value at the front of the same array moves a million values.
Jump to the 10 practice questionsYou will learn
- Tell an interface from the structure behind it
- Count the steps of reading, inserting and removing in an array
- See why a doubling array makes push cheap on average
1Explain
Interface and data structure
A program that keeps a list of names, a queue of print jobs or a table of prices has to store that data somewhere. It also has to answer questions about it: what is the third item, is this name in the list, which job is next? A data structure is a way of storing data together with the methods that answer those questions. MIT's 6.006 course separates two ideas here.
2Explore
One block of memory
An array stores its values in one unbroken block of memory, each value in a cell of the same size, numbered from 0. That layout is what makes arrays fast to read. If the block starts at address s and each cell takes c bytes, then a[i] lives at address s + i × c. The computer works that out with one multiplication and one addition and jumps straight there, whether i is 3 or 3,000,000. MIT's notes list "get at(i)" and "set at(i, x)" for an array as Θ(1), meaning the cost does not grow with the length.
Read any cell: the cost is 1 step wherever it is.
Press a button: each one runs one operation and shows what it cost.
[7,3,9,4,6]Total steps 0
3Problem
Reading far away
In this unit's step count, how many steps does reading a[700000] from an array of 1,000,000 values take?
Hint
The address is worked out with one multiplication and one addition.
Solution
Answer: 1
The address is start + 700000 × cell size, found by arithmetic, so the read is one step.
4Explore
Changing the front
The same layout makes changes in the middle slow. Suppose the array holds 7, 3, 9, 4, 6 and you want 1 at the front. There is no gap in front of 7, so every value has to move one cell to the right first, starting from the last one so nothing is overwritten. That is 5 moves and 1 write: 6 steps. Removing the front value is the mirror image: read it, then move the other 4 values one cell left. Inserting at position i in an array of n values costs n − i moves plus one write, so the front is the worst place and the end is the best.
unshift puts a value at the front, shift removes the front, push adds at the end. Compare the step counts.
Press a button: each one runs one operation and shows what it cost.
[7,3,9,4,6]Total steps 0
5Problem
Insert at the front
An array holds 7, 3, 9, 4, 6 with room to spare. How many steps does inserting a value at the front take (moves plus the write)?
Hint
Every value moves one cell right, then one write.
Solution
Answer: 6
All 5 values move one cell right, then the new value is written: 5 + 1 = 6.
6Problem
Remove the front
Same array of 5 values: how many steps does removing the front value take (1 read plus the moves)?
Hint
1 read, then the other values move left.
Solution
Answer: 5
Read the front value, then move the other 4 values one cell left: 1 + 4 = 5.
7Problem
Insert in the middle
Inserting at position 2 into an array of 5 values (positions 0 to 4) with room: how many steps?
Hint
Only positions 2, 3 and 4 move.
Solution
Answer: 4
Positions 4, 3 and 2 move right (5 − 2 = 3 moves), then 1 write: 4.
8Explore
When the block is full
A block of memory has a fixed size, so what happens when you add a value and every cell is taken? The array has to ask for a new, larger block and copy every value across before it can write the new one. In the lab, pushing onto the full block of 5 costs 5 copies and 1 write. If the array grew by just one cell each time, every push would copy everything, and n pushes would cost about n²/2 copies.
The block holds 5 values and is full. The first push copies all 5 into a block twice as big; the next pushes cost 1 step each.
Press a button: each one runs one operation and shows what it cost.
[7,3,9,4,6]Total steps 0
9Problem
A push on a full block
A doubling array holds 5 values and its capacity is 5. You push one more value. How many steps does that push take?
Hint
Copy 5, then write 1.
Solution
Answer: 6
The block is full: copy 5 values into a new block of 10, then write the new value. 5 + 1 = 6.
10Problem
The new capacity
After that push, what is the capacity?
Hint
Doubling.
Solution
Answer: 10
Doubling turns capacity 5 into 10, so the next four pushes cost 1 step each.
11Explore
Doubling: cheap on average
The fix described in MIT's notes is to grow by a lot at once, for example by doubling. Starting from capacity 1, the copies happen when the array holds 1, 2, 4, 8 and 16 values. So 17 pushes cost 1 + 2 + 4 + 8 + 16 = 31 copies in total, fewer than 2 per push. A single push can still be slow, but any long run of pushes averages out to a constant cost per push. This is called amortized Θ(1) time. A JavaScript array behaves this way from the outside: MDN describes arrays as resizable, and push and pop work at the end, which is the cheap end.
Start with room for 1 value and keep pushing. The copies come at 1, 2, 4 and 8 values, and the total stays under 3 steps per push.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
12Problem
17 pushes
Starting from capacity 1 and doubling, how many copies do 17 pushes make in total?
Hint
1 + 2 + 4 + 8 + 16.
Solution
Answer: 31
Copies happen at sizes 1, 2, 4, 8 and 16: 1 + 2 + 4 + 8 + 16 = 31.
13Problem
Amortized
Why is push on a doubling array called amortized Θ(1)?
Hint
Look at the total over many pushes, not at one push.
Solution
Answer: Copies are rare, so the total over n pushes stays below a constant times n
Some pushes copy everything, but they are spread out so the average per push is constant.
14Explain
The costs side by side
const a = [7, 3, 9, 4, 6];
console.log(a[3]); // 4, one step
a.push(8); // cheap: the end
a.unshift(1); // every value moves one cell right
console.log(a.join(" ")); // 1 7 3 9 4 6 84
1 7 3 9 4 6 8| Operation on n values | Steps in the lab | Grows like |
|---|---|---|
| Read or write a[i] | 1 | Θ(1) |
| Insert at the front | n moves + 1 write | Θ(n) |
| Remove the front | 1 read + (n − 1) moves | Θ(n) |
| Push at the end (room left) | 1 | Θ(1) |
| Push at the end (block full) | n copies + 1 write | Θ(n) once, Θ(1) amortized |
15Problem
Interface or structure?
In MIT 6.006 terms, "insert last(x) and delete last()" is
Hint
It lists operations, not how they are done.
Solution
Answer: an interface
It lists operations you can ask for (here, the stack interface), not how they are done.
16Problem
The last index
An array has length n and counts from 0. What is the index of its last value?
Hint
Counting starts at 0.
Solution
Answer: n − 1
Indexes run 0, 1, ..., n − 1, which is n positions.
17Practice
Insert without splice
Finish insertAt without using splice or unshift. The program should print 1 7 3 9 4 6 and then 5.
1 7 3 9 4 6
5const a = [7, 3, 9, 4, 6];
let moves = 0;
function insertAt(a, i, v) {
// First move a[a.length - 1], then the one before it, ... down to a[i],
// each one cell to the right (add 1 to moves each time). Then write v.
a[i] = v;
}
insertAt(a, 0, 1);
console.log(a.join(" "));
console.log(moves);
Hint
Move from the end towards i, so no value is overwritten before it has moved.
A solution
const a = [7, 3, 9, 4, 6];
let moves = 0;
function insertAt(a, i, v) {
for (let k = a.length - 1; k >= i; k--) {
a[k + 1] = a[k];
moves++;
}
a[i] = v;
}
insertAt(a, 0, 1);
console.log(a.join(" "));
console.log(moves);18Practice
A doubling array
Simulate 17 pushes into a doubling array that starts with room for 1 value. It should print the final capacity 32 and the total number of copies 31.
32
31let capacity = 1, length = 0, copies = 0;
for (let k = 0; k < 17; k++) {
// If length equals capacity: add length to copies, then double capacity.
length++;
}
console.log(capacity);
console.log(copies);
Hint
Double the capacity; growing by one would copy on every push.
A solution
let capacity = 1, length = 0, copies = 0;
for (let k = 0; k < 17; k++) {
if (length === capacity) {
copies += length;
capacity *= 2;
}
length++;
}
console.log(capacity);
console.log(copies);19Explain
Common mistakes
const a = [7, 3, 9, 4, 6];
for (let k = 0; k < a.length - 1; k++) a[k + 1] = a[k];
a[0] = 1;
console.log(a.join(" "));1 7 7 7 7const a = [7, 3, 9, 4, 6];
for (let k = a.length - 1; k >= 0; k--) a[k + 1] = a[k];
a[0] = 1;
console.log(a.join(" "));1 7 3 9 4 6Moving from the front copies 7 over 3 before 3 has moved, then over 9, and so on. Start from the last value.
20
Summary
- An interface lists operations; a data structure is how they are done.
- An array keeps values in one block, so a[i] is one step.
- Inserting or removing near the front moves about n values.
- A doubling array makes push amortized Θ(1): 17 pushes from capacity 1 copy 31 values.