software-engineer-blog logoSoftware Engineer Blog

Module 3 · Complexity and data structures

Unit 10 of 49

Unit 10 · Module 3 · Complexity and data structures

Arrays vs linked lists (and why arrays usually win)

The textbook says O(1) insert. The machine disagrees.

Unit 10 of the free 49-unit computer-science course, in complexity and data structures. 1 topic to watch or read, 2 interview questions answered in full and a short self-check.

Watch or read

One topic makes up this unit. Take each one whichever way suits you, then answer the questions below.

Arrays vs linked lists explained in detail

The textbook says a linked list inserts in O(1) and an array inserts in O(n), so the linked list should win. On real hardware the array wins almost every time — and the reason is not in the code, it's in where the data physically sits. Measured: the same ten million numbers, the same O(n) walk, 0.53s vs 1.53s. Here's contiguity, the 64-byte cache line, the prefetcher, and pointer chasing — plus the experiment that proves the cause with no linked list in it at all.

ReelRead

Interview questions this unit unlocks

Asked out loud, answered out loud. Read the answer, then say it in your own words.

Array or linked list — and why does the textbook answer usually lose?

The textbook says a linked list wins on insertion because it is O(1) once you hold the node, while an array is O(n). Real hardware disagrees, because the array is contiguous: the CPU fetches a whole cache line at a time and prefetches the next one, so scanning it is nearly free, while every node in a linked list is a separate pointer chase into unpredictable memory. Shifting a few thousand contiguous bytes routinely beats following a few hundred pointers.

The honest exception: a linked list wins when you are splicing large elements around, or already hold a pointer to the node, and never traverse to find it.

When do you actually need a linked list?

When you need stable references to elements while the container changes around them, or O(1) splicing of whole ranges. An LRU cache is the classic case — a hash map holds pointers straight to nodes in a doubly-linked list, so touching a key moves it to the front without touching anything else. That is a structural need, not a performance one.

Self-check — 3 questions

Answer alone, at 2am, with no interviewer in the room.

Part of Everything You Need to Know About Computer Science.