Memory Layout Trade-Offs: Arrays vs. Linked Lists
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Evaluate contiguous arrays and node-based linked lists for maintaining an ordered sequence of items (such as [14, 28, 42, 56, 70]), explaining how physical layout in RAM governs random-index lookups, element insertions/removals, full-sequence scans, and real wall-clock execution speed.
Address three core engineering distinctions in your comparison:
- Separate a fixed-capacity buffer from a geometrically resizing dynamic array when analyzing growth overhead, slack space, and element-address stability.
- State explicitly what position handle a linked-list update receives — a numeric index
i, a pointer to the target node, or a pointer to the preceding node — because each input changes the asymptotic work. - Explain which sequence workloads motivate unrolled linked lists that pack
Bconsecutive items inside every list node.
Also note the workload clarifying questions you would ask before selecting a structure in production (such as random-offset reads versus sequential scans, index-based versus iterator-based edits, and pointer/iterator validity guarantees across mutations).
Scope & Expectations
- Contrast fixed-size and dynamically resized contiguous buffers across amortized append cost, worst-case reallocation spikes, unused slack capacity, and pointer/iterator invalidation.
- Break down singly versus doubly linked list costs across all three position inputs (numeric offset
i, predecessor pointer, and target node pointer), accounting for both locating the position and rewiring links. - Connect
O(n)traversal and middle-insertion behavior to hardware realities:64-byte CPU cache lines, hardware stride prefetching, SIMD vectorization, per-node allocator overhead, and dependent pointer-chasing stalls. - Show how unrolled linked lists (
Belements per node) trade bounded in-block shifts and slack slots forB-fold fewer pointer hops and cache-friendly intra-node scans.
Step-by-step walkthrough
Picture the four memory layouts
Every performance difference between arrays and linked lists comes directly from how elements sit in RAM:
1. Fixed-size array (capacity = 6 chosen once at creation, logical size = 4): base -> [ 14 | 28 | 42 | 56 | -- | -- ] Address of a[i] = base + i * elem_bytes 2. Resizable (dynamic) array (logical size = 4, capacity = 8; grows geometrically when full): base -> [ 14 | 28 | 42 | 56 | -- | -- | -- | -- ] 3. Singly linked list (each node separately allocated anywhere on the heap): head -> [14 | next] ---> [28 | next] ---> [42 | next] ---> [56 | null] 4. Doubly linked list (each node points both forward and backward): head -> [null | 14 | next] <-> [prev | 28 | next] <-> [prev | 42 | null] <- tail- An array stores elements in one contiguous block, so any element's memory address is known immediately from arithmetic (
base + i * elem_bytes). - A linked list knows only
head(and optionallytail); the memory address of nodek + 1lives inside nodek, so nodes must be visited one hop at a time.
Throughout the examples below, we use
n = 1,000,000int64(8-byte) integers as a concrete benchmark.- An array stores elements in one contiguous block, so any element's memory address is known immediately from arithmetic (
Indexed reads and dependent pointer hops
- Fixed or dynamic array —
O(1)worst case: Readinga[500_000]computesbase + 500_000 * 8and performs one memory load (~1 nsin L1 cache, up to~60–100 nsif cold in DRAM). Reading index500,000costs the exact same work as reading index0. - Singly linked list —
O(i): Reaching indexifollowsinextpointers fromhead(500,000hops for index500,000). - Doubly linked list with
tail—O(min(i, n - 1 - i)): Starts fromheadifi < n / 2ortailotherwise, which still needs500,000hops at the midpointi = 500,000.
Crucially, linked-list hops are dependent loads (also called pointer chasing, where the CPU cannot request the next memory address until the current load returns from RAM). If nodes are scattered across the heap so each hop misses cache (
~60–100 ns),500,000serial misses take30–50 ms— roughly half a million times slower thana[500_000]. For the same reason, binary search on a sorted linked list still takesO(n)time because jumping to the middle node requires walkingn / 2pointers.- Fixed or dynamic array —
Insertion and deletion: separate the three input cases
Saying "linked-list insertion is
O(1)" is incomplete unless you state what input identifies the position: an integer indexi, a predecessor node pointerpred, or a target node pointerp.Operation Fixed array* Dynamic array Singly linked Doubly linked (+tail) Append at end (i = n) O(1) if room O(1) amortized, O(n) grow O(1) with tail (else O(1) O(n) walk) Delete at end (i = n - 1) O(1) O(1) O(n) find new tail O(1) Insert / delete at front (i = 0) O(n) shift O(n) shift O(1) O(1) Input A: by index i O(n - i) shift O(n - i) shift (O(n) grow) O(i) walk + O(1) link O(min(i,n-i)) + O(1) Input B: given predecessor `pred` N/A N/A O(1) after `pred` O(1) after `pred` Input C: given target node `p` itself N/A N/A O(1) after `p`; O(1) before, after, O(n) before / delete p or delete `p`*Assuming the fixed-capacity buffer tracks a logical
size <= capacityand raises an overflow error whensize == capacity.Three practical consequences stand out:
- By index
i(Input A), arrays often beat linked lists in wall-clock time: Inserting ati = 500,000in our1,000,000-integer array shifts500,000 * 8 = 4 MBforward using one sequentialmemmove(< 0.5 mson modern RAM bandwidth), whereas walking500,000scattered list nodes takes30–50 msbefore theO(1)pointer relink even happens! - Given predecessor
pred(Input B), singly linked lists areO(1): Splicing afterpred(new_node.next = pred.next; pred.next = new_node) or unlinkingpred.next(pred.next = pred.next.next) touches two pointers with zero search. - Given only node
p(Input C), singly linked lists cannot go backward: Deletingpor inserting beforeprequires walking fromheadinO(n)to findpred(copyingp.next.valintopfails on the tail node and silently invalidates external pointers top.next). A doubly linked list readsp.prevdirectly inO(1), which is why structures like LRU caches pair a hash map (key -> node_ptr) with a doubly linked list.
- By index
Capacity growth: fixed vs. dynamic arrays and address stability
- Fixed-size array: Allocates
capacityslots once and never reallocates. Appending is worst-caseO(1)untilsize == capacity, at which point growth is impossible without manually allocating a new buffer. - Dynamic array (
std::vector,ArrayList, Pythonlist): Automatically reallocates a larger contiguous block by a constant growth factor (typically2xor1.5x) wheneversize == capacity, copying allnitems over. Growing by doubling from1to1,024copies1 + 2 + 4 + ... + 512 = 1,023items across1,024appends — less than1copy per append, making append amortizedO(1)(averaging occasional expensive resizes over many cheap appends). By contrast, growing by a fixed+16slots copiesO(n)items every16appends forO(n^2)total work. - Costs of dynamic growth and shifting:
- Memory slack: Right after doubling, up to
50%of the buffer sits unused. - Resize latency spikes: The single append that hits capacity takes
O(n)time (mitigated byreserve(expected_n)). - Pointer and iterator invalidation: Reallocation moves every element to a brand-new memory block, invalidating all raw pointers, references, and iterators into the array; even without reallocation, inserting or deleting at index
ishiftsa[i..n-1], invalidating pointers/iterators fromionward.
- Memory slack: Right after doubling, up to
- Linked list address stability: Nodes never move in memory once allocated, so pointers and iterators to any surviving node stay valid across arbitrary insertions and deletions elsewhere.
- Fixed-size array: Allocates
Traversal: why two O(n) scans differ by 10x–50x
Scanning all
nelements isO(n)in both structures, yet contiguous arrays routinely run an order of magnitude faster on real CPUs:64-byte CPU cache lines: CPUs fetch RAM in64-byte cache lines. One cache line of anint64array delivers8consecutive elements (100%useful bytes); a scattered list node pulls a whole64-byte line just to read one8-byte value.- Hardware prefetching and overlapping reads: Sequential addresses (
base, base + 8, base + 16, ...) trigger the hardware prefetcher to load upcoming cache lines into L1 cache (~1 ns) ahead of the loop. Linked-list pointer chasing is unpredictable and serializes DRAM misses (~60–100 nseach). - Per-node memory footprint: Storing
1,000,000int64s in an array uses8 MB. A doubly linked node needs24bytes (prev + value + next), rounded to32bytes with heap-allocator headers —32 MB(4xmore memory traffic, spilling out of L3 cache much sooner). - SIMD vectorization: Compilers sum
4–8contiguous array elements per CPU instruction using SIMD (Single Instruction, Multiple Data); dependentnode = node.nextloops cannot vectorize.
You can observe the cost of non-sequential memory access alone in a few lines of Python over the exact same
40 MBarray:import time import numpy as np n = 5_000_000 values = np.arange(n, dtype=np.int64) shuffled = np.random.default_rng(0).permutation(n) for label, order in [("sequential", np.arange(n)), ("scattered", shuffled)]: best_ms = float("inf") for _ in range(3): start = time.perf_counter() _ = int(values[order].sum()) elapsed_ms = (time.perf_counter() - start) * 1000.0 best_ms = min(best_ms, elapsed_ms) print(f"{label:10s}: {best_ms:.2f} ms")Unrolled linked lists and how to choose
What if a workload needs both indexed lookups/scans faster than pointer-per-element lists and middle insertions without shifting
O(n)array elements? That motivates an unrolled linked list, where each node stores a small contiguous array of up toBelements alongside an occupancycount:Block capacity B = 4 (every non-tail node kept at least B/2 = 2 full): head -> [cnt=3 | a0 a1 a2 -- | next] -> [cnt=4 | a3 a4 a5 a6 | next] -> [cnt=2 | a7 a8 -- -- | null]How operations behave with block capacity
B(keeping nodes>= B / 2full by splitting full nodes on insert and borrowing/merging on delete):- Indexed read
get(i)—O(n / B)hops: Add nodecounts to skip entire blocks at once, then index directly inside the target block inO(1). - Insert / delete by index
i—O(n / B + B): Walk at most2n / Bnodes, then shift at mostB - 1contiguous elements inside one block (splitting into twoB / 2blocks if full). - Traversal & memory: Only
1pointer hop per~Belements; inside each block, elements sit contiguously for cache lines, prefetching, and SIMD, while pointer overhead shrinks by a factor ofB(trading up to50%empty slots per block).
Concrete comparison at
n = 1,000,000andB = 64(512bytes =8cache lines ofint64s per node):Metric at n = 1,000,000 Dynamic array Doubly linked list Unrolled list (B = 64) Reach index 500,000 1 memory read 500,000 hops 7,813 to 15,625 hops Edit work once at index 500,000 Shift 500,000 O(1) pointer writes Shift <= 63 in 1 block Pointer hops in full n-item scan 0 1,000,000 15,625 to 31,250Choosing
B = sqrt(n)(B = 1,000forn = 1,000,000) minimizesn / B + BtoO(sqrt(n))per indexed insert; in practiceBis sized to2–8cache lines (32–128elements), and ifO(log n)indexed access + insert is required, an order-statistic B-tree or rope adds tree routing on top of those blocks.Mapping key workload questions to your final production choice:
- Mostly random-offset or sequential reads? Choose a contiguous array (
fixed-sizeif peak length is bounded;dynamicwithreserveotherwise). - Frequent edits at an already-held node/iterator, or strict element-address stability required? Choose a doubly linked list (
singly linkedif memory is tight and you always hold the predecessor). - Large sequences mixing indexed access, sequential scans, and middle inserts/deletes by index? Choose an unrolled linked list (or B-tree/rope for
O(log n)scale).
- Indexed read
Intuition & how it works
Picture an array as numbered stadium seats 0, 1, 2, ... bolted side by side in one row, and a linked list as a scavenger hunt where each clue card tells you the hiding spot of the next card. In the stadium row, jumping to seat 500 takes instant arithmetic (row_start + 500 * seat_width), and sweeping down the row inspects eight adjacent seats per glance — though squeezing someone into seat 2 forces everyone from seat 2 onward to slide over one spot. In the scavenger hunt, splicing a new card right after a card you already hold in your hand only rewrites two clue arrows, but looking up the 500-th card forces you to visit all 500 hiding spots one after another.
Textbook summaries often mislead engineers by claiming "arrays have O(n) insert and linked lists have O(1) insert" without asking how you got to the insertion spot or how CPUs read RAM. If the caller gives you an index i, a linked list still pays O(i) serial pointer hops just to reach position i — and chasing 500,000 scattered heap pointers across RAM (30–50 ms of cache misses) is much slower than shifting 500,000 contiguous integers with a single sequential memory copy (< 0.5 ms). Conversely, if you store several consecutive elements inside each list node (an unrolled linked list), you skip whole blocks at a time while confining shifts to one tiny block.
Walk through 5 integers [14, 28, 42, 56, 70] on two operations:
- Indexed read
get(3)(want56): The array computesbase + 3 * 8and reads56in1memory access; the singly linked list follows3dependent pointershead(14) -> 28 -> 42 -> 56. - Insert
35at index2: The dynamic array shifts[42, 56, 70]one slot right (3contiguous moves) and writes35ata[2]; the singly linked list walkshead(14) -> 28(2pointer hops to find the predecessor) and rewires28 -> 35 -> 42(2pointer writes). Had the caller already held a pointer to node28, the list would skip the walk and finish inO(1).
Key points
- Contiguous vs. node-based layout: Arrays store elements back-to-back in one block (
address = base + i * elem_bytes), giving worst-caseO(1)indexed reads; linked lists allocate each node separately on the heap, requiringO(i)hops (O(min(i, n - i))in a doubly linked list withtail) of dependent loads (pointer chasing where addressk + 1is unknown until nodekarrives). - Fixed vs. resizable arrays: A fixed-size array has a hard capacity chosen at creation and never moves; a dynamic array grows by a constant factor (e.g.,
2x), achieving amortizedO(1)append (1,023total copies across1,024appends) at the cost of up to50%slack capacity, occasionalO(n)resize spikes, and address/iterator invalidation whenever reallocation or shifting occurs. Linked-list node addresses never move until deleted. - Three distinct linked-list inputs: Given index
i, insert/delete isO(i)(O(min(i, n - i))doubly linked) because reaching the spot dominates; given a predecessor pointerpred, insert-after and delete-next areO(1)in both singly and doubly linked lists; given only the target node pointerp, delete or insert-before isO(1)in a doubly linked list (p.prev) vs.O(n)in a singly linked list (must walk fromheadto locatepred, includingpop_backat the tail). - Hardware traversal gap: Both traverse in
O(n), yet arrays pack8int64s per64-byte cache line, trigger the hardware prefetcher, overlap memory reads, and vectorize with SIMD (Single Instruction, Multiple Data), whereas scattered list nodes incur serial~60–100 nsDRAM misses and2x–4xmemory overhead from pointers plus allocator headers. - Unrolled linked lists (
Bitems per node): Keeping nodes>= B / 2full reduces indexed lookup hops fromO(n)toO(n / B), bounds insert/delete shifts toO(B)inside a single cache-friendly block, amortizes pointer overhead acrossBitems, and achievesO(sqrt(n))indexed updates whenB = sqrt(n).
Common mistakes
- Calling linked-list insertion
O(1)without specifying the input: Given an integer indexi, locating the node takesO(i)pointer hops;O(1)holds only when you already hold the node (doubly linked) or its predecessor (singly linked). - Forgetting singly linked lists cannot step backward in
O(1): Deleting a given nodep, inserting beforep, or popping the tail (i = n - 1) all requireO(n)traversal fromheadto find the predecessor, even if you maintain atailpointer. - Growing dynamic arrays by a fixed additive increment (
+K) instead of a constant factor (2x): Additive growth copiesO(n)elements everyKappends, degradingnappends fromO(n)total (O(1)amortized) toO(n^2). - Holding raw pointers or iterators across dynamic-array growth or middle edits: A
push_backthat triggers reallocation moves the entire buffer and dangles every pointer into the old array; middle insert/delete also invalidates pointers at and after indexi. - Proposing binary search on a sorted linked list: Binary search still runs in
O(n)time on a linked list because jumping to midpointn / 2requires walkingn / 2pointers (O(n / 2 + n / 4 + ...) = O(n)). - Picking a linked list to speed up middle insertions by index: On modern hardware, a contiguous
memmoveofO(n - i)elements beats chasingO(i)scattered heap pointers up to surprisingly largen.
Follow-up questions
- What do you gain and give up by packing B elements into each unrolled-list node instead of storing a single item per node? Storing up to
Bconsecutive elements per node (kept at leastB / 2full) trades small local array shifts and up to50%empty node slack forB-fold fewer pointer hops, far lower pointer/allocator memory overhead (1pointer per~Bitems instead of1–2per item), and contiguous cache-line scans inside every node. Forn = 1,000,000andB = 64, reaching index500,000drops from500,000pointer hops to7,813–15,625hops while inserting shifts at most63elements in one512-byte block (splitting into two32-item nodes on overflow and borrowing/merging on underflow). SettingB = 1degenerates into a standard linked list (O(n)walk,O(1)edit), settingB = ndegenerates into one array (O(1)read,O(n)shift), and settingB = sqrt(n)balances both phases atO(sqrt(n))(though note individual element addresses inside a node can shift by up toBpositions on edits). - Both array scans and linked-list scans perform O(n) visits—why is the array scan often an order of magnitude faster on modern CPUs? Big-O counts abstract loop iterations (
nvisits) while assuming every memory read costs1unit, whereas on real CPUs an L1 cache hit costs~1 nsand a DRAM cache miss costs~60–100 ns. Scanning a contiguousint64array loads8useful values in every64-byte cache line, follows a constant address stride so the hardware prefetcher pulls upcoming cache lines into L1 before the loop asks for them, allows out-of-order execution to overlap independent reads, and lets the compiler process4–8elements per instruction via SIMD. By contrast, a linked list storesnextinside each heap-allocated node (2x–4xlarger total footprint with pointers and allocator headers), creating a dependent load chain where the CPU stalls waiting for nodekbefore it even knows the address of nodek + 1— turning1,000,000scattered visits into tens of milliseconds vs. well under a millisecond for the array.
Follow-up questions
- What do you gain and give up by packing B elements into each unrolled-list node instead of storing a single item per node?
- Both array scans and linked-list scans perform O(n) visits—why is the array scan often an order of magnitude faster on modern CPUs?
Similar questions
- Unrolled Linked List Lookup and Insertion
- Vectorized MSE and Linear Regression
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging