edubun
English
1 / 20

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 questions

You 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 8
Output
4
1 7 3 9 4 6 8
Operation on n valuesSteps in the labGrows like
Read or write a[i]1Θ(1)
Insert at the frontn moves + 1 writeΘ(n)
Remove the front1 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.

Expected output
1 7 3 9 4 6
5
Your code
const 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.

Expected output
32
31
Your code
let 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

Mistake
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(" "));
Output
1 7 7 7 7
Fixed
const 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(" "));
Output
1 7 3 9 4 6

Moving 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.

Next unitStacks
Full text · The whole lesson as one text

What a data structure is

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. The interface says which operations you can ask for, such as "get the item at position i" or "add an item at the end". The data structure is how those operations are actually carried out in memory. One interface can have several data structures behind it, and they can differ hugely in speed.

This course counts steps, as the algorithms course does, so that two structures can be compared without a stopwatch. In this unit a step is reading or writing one cell of memory. The lab below counts them for you.

One block of cells, side by side

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.

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.

An array of five values in a block of five cells. Move the slider to choose i, then read, insert or remove. Pushing onto the full block copies everything into a block twice as large.

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 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.

Operation on n valuesSteps in the labGrows like
Read or write a[i]1Θ(1)
Insert at the frontn moves + 1 writeΘ(n)
Remove the front1 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
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 8
BackgroundArrays are older than most programming languages. Early machines stored a table as numbered words in memory, and programmers computed the address of entry i by hand, exactly as the formula above does. Fortran, released by IBM in 1957, made arrays part of the language so that people could write A(I) and let the compiler do the address arithmetic. Fortran counted from 1. C and JavaScript count from 0, which fits the formula: a[0] sits at the start address itself.
Key points
  • 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.

Practice questions from Arrays on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18