Arrays and Linked Lists
Understand why array indexing is O(1) but inserting is O(n), how dynamic arrays grow in amortized constant time, and when a linked list is the better fit.
Welcome back!
Step 1 of 10Learn
Why arrays are fast to read
An array stores its elements in one contiguous block of memory, side by side. If an array of 4-byte integers starts at memory address 1,000, then element 0 is at 1,000, element 1 at 1,004, element 2 at 1,008, and element i at 1,000 + 4i. The computer doesn't search for element 500; it calculates the address with one multiplication and one addition. That's why access by index is O(1), no matter how large the array is.
Contiguous storage has a second, less obvious benefit: cache locality. Processors load memory in chunks, so reading one element pulls its neighbors into the fast CPU cache. Looping through an array is therefore much faster in practice than its Big O alone suggests.
The price comes when you change the middle. To insert a new element at index 0 of an array with n elements, every existing element must shift one position right to make room: n moves, so O(n). Deleting from the front shifts everything left, also O(n). Inserting or removing at the end is cheap, O(1), as long as there's space.
Searching an unsorted array for a value is O(n), since you may need to check every element. If the array is sorted, binary search finds it in O(log n), but keeping it sorted makes each insertion O(n).
So arrays are excellent when you read by position a lot and mostly add or remove at the end.
Step 2 of 10Practice · Work it out
An array holds 1,000 elements with no gaps. How many existing elements must be shifted to insert a new element at index 0?
Step 3 of 10Learn
Dynamic arrays and amortized cost
Classic arrays have a fixed size. But JavaScript arrays, Python lists, Java's ArrayList and C++'s vector all grow as you append. They're dynamic arrays, and the trick behind them is simple: keep some spare capacity. When the array is full and you append, allocate a new block, typically double the size, copy every element over, and then add the new one.
That copy is O(n), so some appends are expensive. But they're rare. Start with capacity 1 and append n items: you copy 1 element when growing to 2, then 2 when growing to 4, then 4, 8, 16 and so on. The total number of copies is 1 + 2 + 4 + ... up to n, which is less than 2n. Spread across n appends, that's fewer than 2 copies per append on average.
This is called amortized O(1): any single append might cost O(n), but the average over a long sequence is constant. It's like a monthly bill that's large once in a while but small when averaged over every day.
The growth factor matters. If the array grew by a fixed amount, say 10 slots each time, resizes would happen every 10 appends and the total copying would be O(n²). Multiplying the capacity, by 2 or 1.5 in many libraries, is what keeps appends cheap.
The trade-off is memory: right after a resize, up to half the capacity may sit empty.
Step 4 of 10Practice · Work it out
A dynamic array starts with capacity 1 and doubles whenever it's full. You append 17 items one at a time. How many element copies happen in total during resizes?
Step 5 of 10Learn
Linked lists
A linked list stores elements in separate nodes scattered anywhere in memory. Each node holds a value and a reference, or pointer, to the next node. The list keeps a reference to the first node, the head; the last node's next is null.
head -> [3 | •] -> [8 | •] -> [5 | null]Because nodes aren't contiguous, there's no address arithmetic. To reach the element at index 500, you start at the head and follow 500 links: access by index is O(n).
The benefit is cheap rearranging. To insert a node at the head, create it, point its next at the old head, and update head: O(1), no shifting. If you already hold a reference to a node, inserting or deleting right after it is also O(1), just a couple of pointer updates. A doubly linked list adds a prev pointer to each node, making deletion of a known node and backward traversal easy, at the cost of more memory.
Linked lists have real downsides. Each node carries pointer overhead. Nodes scattered in memory defeat the CPU cache, so traversing a linked list is often several times slower than traversing an array of the same length. And finding the position to insert at is still O(n) unless you already have a reference to it.
They're most useful as building blocks: queues, the hash table chains you'll see shortly, and structures like an LRU cache that combine a hash table with a doubly linked list.
Step 6 of 10Compare
Dynamic array vs. singly linked list
| Aspect | Dynamic array | Singly linked list |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert or delete at the front | O(n): shift everything | O(1) |
| Append at the end | Amortized O(1) | O(1) with a tail pointer, otherwise O(n) |
| Insert after a node you hold | O(n) shifting | O(1) |
| Search for a value | O(n), or O(log n) if sorted | O(n) |
| Memory and cache | Compact, cache-friendly | Extra pointer per node, scattered |
Step 7 of 10Practice · Code challenge
Nodes look like { val: 3, next: nodeOrNull }. Write reverse(head) that reverses a singly linked list in place and returns the new head. The helpers fromArray and toArray are provided for the tests; don't change them.
toArray(reverse(fromArray([1, 2, 3, 4])))toArray(reverse(fromArray([7])))toArray(reverse(fromArray([])))toArray(reverse(fromArray([5, 9])))
Step 8 of 10Learn
Choosing between them
In everyday programming, dynamic arrays are the default, and for good reason. Most programs read data far more than they rearrange it, appending at the end is amortized O(1), and arrays' cache-friendliness makes them fast in practice even for operations where linked lists win on paper. Benchmarks often show arrays beating linked lists for insertion into the middle of small and medium collections, because shifting contiguous memory is so fast.
Reach for a linked list, or a structure built on one, when:
- You need constant-time insertion and deletion at both ends or at positions you already hold references to, such as in a queue or an LRU cache.
- Elements are large or must not move in memory because other parts of the program point to them.
- You're implementing other structures, like hash table chains or adjacency lists for graphs.
A few practical notes for JavaScript:
pushandpopwork at the end and are fast.unshiftandshiftwork at the front and are O(n) in general, because elements shift.splicein the middle is O(n).arr[i]is O(1).
Knowing these costs helps you spot slow code. A loop that calls shift() on a large array every iteration is quietly O(n²), and it's one of the most common performance bugs in beginner code that processes a queue.
Step 9 of 10Practice · Sort into groups
Sort each operation by its typical time complexity.
Tap an item, then tap its group (or drag it there).
Step 10 of 10Practice · Choose one
A program reads millions of elements by position and only ever adds new elements at the end. Which structure fits best?
Lesson complete!