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 B consecutive 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 (B elements per node) trade bounded in-block shifts and slack slots for B-fold fewer pointer hops and cache-friendly intra-node scans.

Step-by-step walkthrough

  1. 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 optionally tail); the memory address of node k + 1 lives inside node k, so nodes must be visited one hop at a time.

    Throughout the examples below, we use n = 1,000,000 int64 (8-byte) integers as a concrete benchmark.

  2. Indexed reads and dependent pointer hops

    • Fixed or dynamic array — O(1) worst case: Reading a[500_000] computes base + 500_000 * 8 and performs one memory load (~1 ns in L1 cache, up to ~60–100 ns if cold in DRAM). Reading index 500,000 costs the exact same work as reading index 0.
    • Singly linked list — O(i): Reaching index i follows i next pointers from head (500,000 hops for index 500,000).
    • Doubly linked list with tail — O(min(i, n - 1 - i)): Starts from head if i < n / 2 or tail otherwise, which still needs 500,000 hops at the midpoint i = 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,000 serial misses take 30–50 ms — roughly half a million times slower than a[500_000]. For the same reason, binary search on a sorted linked list still takes O(n) time because jumping to the middle node requires walking n / 2 pointers.

  3. 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 index i, a predecessor node pointer pred, or a target node pointer p.

    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 <= capacity and raises an overflow error when size == capacity.

    Three practical consequences stand out:

    1. By index i (Input A), arrays often beat linked lists in wall-clock time: Inserting at i = 500,000 in our 1,000,000-integer array shifts 500,000 * 8 = 4 MB forward using one sequential memmove (< 0.5 ms on modern RAM bandwidth), whereas walking 500,000 scattered list nodes takes 30–50 ms before the O(1) pointer relink even happens!
    2. Given predecessor pred (Input B), singly linked lists are O(1): Splicing after pred (new_node.next = pred.next; pred.next = new_node) or unlinking pred.next (pred.next = pred.next.next) touches two pointers with zero search.
    3. Given only node p (Input C), singly linked lists cannot go backward: Deleting p or inserting before p requires walking from head in O(n) to find pred (copying p.next.val into p fails on the tail node and silently invalidates external pointers to p.next). A doubly linked list reads p.prev directly in O(1), which is why structures like LRU caches pair a hash map (key -> node_ptr) with a doubly linked list.
  4. Capacity growth: fixed vs. dynamic arrays and address stability

    • Fixed-size array: Allocates capacity slots once and never reallocates. Appending is worst-case O(1) until size == capacity, at which point growth is impossible without manually allocating a new buffer.
    • Dynamic array (std::vector, ArrayList, Python list): Automatically reallocates a larger contiguous block by a constant growth factor (typically 2x or 1.5x) whenever size == capacity, copying all n items over. Growing by doubling from 1 to 1,024 copies 1 + 2 + 4 + ... + 512 = 1,023 items across 1,024 appends — less than 1 copy per append, making append amortized O(1) (averaging occasional expensive resizes over many cheap appends). By contrast, growing by a fixed +16 slots copies O(n) items every 16 appends for O(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 by reserve(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 i shifts a[i..n-1], invalidating pointers/iterators from i onward.
    • 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.
  5. Traversal: why two O(n) scans differ by 10x–50x

    Scanning all n elements is O(n) in both structures, yet contiguous arrays routinely run an order of magnitude faster on real CPUs:

    1. 64-byte CPU cache lines: CPUs fetch RAM in 64-byte cache lines. One cache line of an int64 array delivers 8 consecutive elements (100% useful bytes); a scattered list node pulls a whole 64-byte line just to read one 8-byte value.
    2. 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 ns each).
    3. Per-node memory footprint: Storing 1,000,000 int64s in an array uses 8 MB. A doubly linked node needs 24 bytes (prev + value + next), rounded to 32 bytes with heap-allocator headers — 32 MB (4x more memory traffic, spilling out of L3 cache much sooner).
    4. SIMD vectorization: Compilers sum 4–8 contiguous array elements per CPU instruction using SIMD (Single Instruction, Multiple Data); dependent node = node.next loops cannot vectorize.

    You can observe the cost of non-sequential memory access alone in a few lines of Python over the exact same 40 MB array:

    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")
    
  6. 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 to B elements alongside an occupancy count:

    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 / 2 full by splitting full nodes on insert and borrowing/merging on delete):

    • Indexed read get(i) — O(n / B) hops: Add node counts to skip entire blocks at once, then index directly inside the target block in O(1).
    • Insert / delete by index i — O(n / B + B): Walk at most 2n / B nodes, then shift at most B - 1 contiguous elements inside one block (splitting into two B / 2 blocks if full).
    • Traversal & memory: Only 1 pointer hop per ~B elements; inside each block, elements sit contiguously for cache lines, prefetching, and SIMD, while pointer overhead shrinks by a factor of B (trading up to 50% empty slots per block).

    Concrete comparison at n = 1,000,000 and B = 64 (512 bytes = 8 cache lines of int64s 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,250
    

    Choosing B = sqrt(n) (B = 1,000 for n = 1,000,000) minimizes n / B + B to O(sqrt(n)) per indexed insert; in practice B is sized to 2–8 cache lines (32–128 elements), and if O(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-size if peak length is bounded; dynamic with reserve otherwise).
    • Frequent edits at an already-held node/iterator, or strict element-address stability required? Choose a doubly linked list (singly linked if 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).

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:

  1. Indexed read get(3) (want 56): The array computes base + 3 * 8 and reads 56 in 1 memory access; the singly linked list follows 3 dependent pointers head(14) -> 28 -> 42 -> 56.
  2. Insert 35 at index 2: The dynamic array shifts [42, 56, 70] one slot right (3 contiguous moves) and writes 35 at a[2]; the singly linked list walks head(14) -> 28 (2 pointer hops to find the predecessor) and rewires 28 -> 35 -> 42 (2 pointer writes). Had the caller already held a pointer to node 28, the list would skip the walk and finish in O(1).

Key points

  • Contiguous vs. node-based layout: Arrays store elements back-to-back in one block (address = base + i * elem_bytes), giving worst-case O(1) indexed reads; linked lists allocate each node separately on the heap, requiring O(i) hops (O(min(i, n - i)) in a doubly linked list with tail) of dependent loads (pointer chasing where address k + 1 is unknown until node k arrives).
  • 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 amortized O(1) append (1,023 total copies across 1,024 appends) at the cost of up to 50% slack capacity, occasional O(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 is O(i) (O(min(i, n - i)) doubly linked) because reaching the spot dominates; given a predecessor pointer pred, insert-after and delete-next are O(1) in both singly and doubly linked lists; given only the target node pointer p, delete or insert-before is O(1) in a doubly linked list (p.prev) vs. O(n) in a singly linked list (must walk from head to locate pred, including pop_back at the tail).
  • Hardware traversal gap: Both traverse in O(n), yet arrays pack 8 int64s per 64-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 ns DRAM misses and 2x–4x memory overhead from pointers plus allocator headers.
  • Unrolled linked lists (B items per node): Keeping nodes >= B / 2 full reduces indexed lookup hops from O(n) to O(n / B), bounds insert/delete shifts to O(B) inside a single cache-friendly block, amortizes pointer overhead across B items, and achieves O(sqrt(n)) indexed updates when B = sqrt(n).

Common mistakes

  • Calling linked-list insertion O(1) without specifying the input: Given an integer index i, locating the node takes O(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 node p, inserting before p, or popping the tail (i = n - 1) all require O(n) traversal from head to find the predecessor, even if you maintain a tail pointer.
  • Growing dynamic arrays by a fixed additive increment (+K) instead of a constant factor (2x): Additive growth copies O(n) elements every K appends, degrading n appends from O(n) total (O(1) amortized) to O(n^2).
  • Holding raw pointers or iterators across dynamic-array growth or middle edits: A push_back that triggers reallocation moves the entire buffer and dangles every pointer into the old array; middle insert/delete also invalidates pointers at and after index i.
  • Proposing binary search on a sorted linked list: Binary search still runs in O(n) time on a linked list because jumping to midpoint n / 2 requires walking n / 2 pointers (O(n / 2 + n / 4 + ...) = O(n)).
  • Picking a linked list to speed up middle insertions by index: On modern hardware, a contiguous memmove of O(n - i) elements beats chasing O(i) scattered heap pointers up to surprisingly large n.

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 B consecutive elements per node (kept at least B / 2 full) trades small local array shifts and up to 50% empty node slack for B-fold fewer pointer hops, far lower pointer/allocator memory overhead (1 pointer per ~B items instead of 1–2 per item), and contiguous cache-line scans inside every node. For n = 1,000,000 and B = 64, reaching index 500,000 drops from 500,000 pointer hops to 7,813–15,625 hops while inserting shifts at most 63 elements in one 512-byte block (splitting into two 32-item nodes on overflow and borrowing/merging on underflow). Setting B = 1 degenerates into a standard linked list (O(n) walk, O(1) edit), setting B = n degenerates into one array (O(1) read, O(n) shift), and setting B = sqrt(n) balances both phases at O(sqrt(n)) (though note individual element addresses inside a node can shift by up to B positions 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 (n visits) while assuming every memory read costs 1 unit, whereas on real CPUs an L1 cache hit costs ~1 ns and a DRAM cache miss costs ~60–100 ns. Scanning a contiguous int64 array loads 8 useful values in every 64-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 process 4–8 elements per instruction via SIMD. By contrast, a linked list stores next inside each heap-allocated node (2x–4x larger total footprint with pointers and allocator headers), creating a dependent load chain where the CPU stalls waiting for node k before it even knows the address of node k + 1 — turning 1,000,000 scattered visits into tens of milliseconds vs. well under a millisecond for the array.

Follow-up questions

Similar questions

More Indeed interview questions

All 3 Indeed questions →