Data Structures & Algorithms / Module 1: Linear data structures

Topic 1.1

Arrays and dynamic arrays

A numbered row you can read at any position in one step, and what happens when the row fills up.

8 min · beginner

Watch: when the row is full, everything moves to a new row twice as long. That's rare, so on average it stays cheap.

01
  • moving now
  • no longer used
Step 1 of 14

An empty array with capacity 2.

Nine pushes into an array that starts with 2 slots. Most pushes just fill a free slot; now and then everything is copied into new storage twice the size.

Like a row of numbered lockers

Picture a row of lockers right next to each other, numbered from 0. To open locker 500 you don't walk past lockers 0 to 499: you know exactly where it is. A computer does the same with an array. Because the elements sit side by side and are the same size, the place of element i can be worked out directly. That's why list[500] is as fast as list[0]: O(1).

When the lockers run out

A row of lockers has a fixed length. If you need more room you can't just extend the end, because something else may already sit next to it. The fix: rent a new row twice as long, move everything over, and carry on. That is what happens behind push in JavaScript, append in Python or ArrayList in Java.

Press Step in the figure. Most pushes just fill a free slot. Now and then there is a big move, but because the size always doubles, the moves get rarer and rarer. Averaged out, each push is still O(1).

What is fast and what is slow

OperationBig-OWhy
list[i]O(1)its place can be worked out
push / pop at the endO(1) on averageonly fills or empties the end
unshift / shift at the frontO(n)every element shifts
inserting in the middleO(n)the elements after it shift
finding a value (includes)O(n)checked one by one
Code, for programmersIndexes start at 0
const list = [10, 20, 30];
list[0];          // 10, the first element
list[2];          // 30, the last element
list[3];          // undefined: there is no fourth
list.push(40);    // [10, 20, 30, 40]

Quiz

  1. Why is list[999] as fast as list[0]?

  2. A dynamic array with capacity 4 is full. What happens on the next push?

  3. Inserting an element at position 0 of an array with n elements takes…

0 of 3 answered.