Skip to content
Tech Interview Prep
Technical interview guide

Linked Lists

Singly/doubly linked lists, pointer manipulation, and the classic two-pointer patterns.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with container behaviour cited from CPython 3.14, the C++ standard containers, and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain what a linked list actually buys and how it changes a production decision.

Answer

The 60-second answer. A linked list buys exactly one thing: O(1) insertion and removal at a node you already hold a reference to. Everything else it does worse than a dynamic array. So the production question is never "list or array" in the abstract: it is "does my algorithm already hold the node?" If yes (LRU cache, free list, lock-free queue) the list wins. If no, you pay O(n) to find the position and you have bought nothing but cache misses.

What it costs in bytes. Assumptions: 64-bit x86-64; C struct {int32_t v; struct node *next;}; Java on HotSpot with compressed oops.

RepresentationPer element1M elements
C int32_t[]4 B4 MB, one allocation
C linked node16 B (4 value + 4 pad + 8 pointer)16 MB, 1M mallocs
Java int[]4 B4 MB
Java LinkedList<Integer>~40 B (24 B Node + 16 B Integer)~40 MB, 1M objects for the GC to trace

What it costs in time. Illustrative, on a server x86-64: a dependent load that misses to DRAM costs ~80–100 ns. Scanning 1M int32 in an array is prefetch-friendly and finishes in roughly 1 ms. Walking 1M scattered nodes is ~1M dependent misses, so ~80–100 ms once the list exceeds L3. Measure on your hardware; the ratio is the point, not the absolute.

C
// splice: unlink the node after `prev` — O(1), no traversal
struct node *victim = prev->next;
prev->next = victim->next;
free(victim);

// reaching position i — i dependent loads, no ILP, no prefetch
struct node *p = head;
for (int k = 0; k < i; k++) p = p->next;

The second loop is why the first one is cheap. Each hop depends on the previous load's result, so the CPU cannot overlap them.

The API trap. In Java, LinkedList.remove(Object) is O(n): it scans. The O(1) removal is only reachable through a ListIterator you already positioned:

Java
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
    if (it.next().equals(target)) { it.remove(); break; }  // O(1) once positioned
}

So "constant-time removal" is a property of your own node class or of an iterator you hold, not of the collection's public surface. That gap is where the slogan breaks.

Failure modes, and how you see them.

  • Accidental O(n²). for (i = 0; i < n; i++) list.get(i) on a LinkedList is quadratic. It shows up as a p99 that grows with input size in a profiler flame graph, not in unit tests with n = 10.
  • Iterator invalidation. Mutating the list outside the iterator throws ConcurrentModificationException: loud, and easy to catch in review.
  • GC and fragmentation. 1M nodes is 1M objects to trace and 1M separate allocations. In Java this shows as GC pause growth; in C, as allocator fragmentation under long uptime.
  • Cache cliff. A list that fits in L2 behaves fine and then degrades sharply past it. Benchmark at production scale, not at 1k elements.

When to actually choose one.

  • LRU cache: HashMap from key to node plus an intrusive doubly linked list for move-to-front. Java's LinkedHashMap with accessOrder=true and removeEldestEntry is this design, already written.
  • Free lists and slab allocators: the node is embedded in the object, so there is no per-element allocation at all.
  • Lock-free queues: a Michael–Scott queue CASes a single next pointer, which an array cannot do without a much heavier scheme.
  • Kernel-style intrusive lists (list_head): zero overhead beyond two pointers, because the links live inside the payload.

Everywhere else (a queue, a stack, a growable sequence) use a dynamic array. In Java that means ArrayDeque over LinkedList for queue workloads: less memory, better locality, no per-node allocation. Reach for the linked list when the algorithm hands you the node; otherwise you are paying the pointer-chase tax for a splice you never get to use.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about why arrays usually win in practice in a system you own?

Answer

The first 90 seconds

"Arrays win" is a claim about a workload, not about a data structure, so I'd start by locating the structure in the hot path: is it walked once per request, or once per element per request? Then I'd measure the two things that actually decide it, cache misses and allocation count, instead of comparing Big-O. The default expectation is that the contiguous version wins, and the reason is mechanical.

Mechanism

Array elements sit in one contiguous block. A 64-byte cache line carries 8 int64s, so one miss feeds eight elements, the hardware prefetcher streams the next lines ahead of the loop, and the TLB needs a handful of pages. A linked list node is a separate allocation reached by a dependent load: the address of node n+1 is inside node n, so the CPU cannot issue the next load until the current one returns. No prefetcher can help, because the next address is unknown until the data arrives. You also pay one allocator call per node, with its header and its fragmentation.

Illustrative arithmetic (1,000,000 int64s, single core, DRAM ~80 ns, streaming ~10 GB/s)

ArrayLinked list
Bytes8 MB~32 MB (16 B node + ~16 B allocator header)
Cache lines touched125,000up to 1,000,000
Allocations1 (plus growth)1,000,000
Time8 MB / 10 GB/s ≈ 0.8 ms1M × 80 ns ≈ 80 ms if each node misses

That is roughly two orders of magnitude, and it is memory-latency bound, not instruction bound. Even if half the nodes hit L3 (~15 ns), you are still in the tens of milliseconds. The array's advantage is not that it does fewer operations; it is that its operations overlap.

Failure modes in a system you own

  • Reallocation spike. Appending past capacity copies the whole buffer. A 1 GB array doubling copies 1 GB: ~100 ms on the request that triggered it. Detected by a p99/p999 latency spike correlated with allocation events in a heap profiler. Fix: reserve capacity, or use a chunked/deque layout.
  • Over-allocation. Capacity can sit at up to 2x live size. Detected by comparing RSS against live-heap bytes from the allocator's stats.
  • Pointer-chase cliff. A linked list that is fine at 1k elements collapses at 1M when the working set exceeds LLC. Detected with perf stat -e LLC-load-misses,instructions and an IPC drop; a unit test at small n never sees it.
  • Fragmentation. A million small nodes fragment the allocator; RSS climbs with flat live heap. Detected via jemalloc/tcmalloc stats and an RSS trend line.
  • Address instability. realloc invalidates pointers into the array. Detected by ASan or a crash shortly after growth.

When the linked list is right

Intrusive lists where you already hold the node (LRU eviction, O(1) splice out of the middle) stable addresses that must not move, lock-free stacks and queues, and elements large enough that the memmove dominates the pointer chase. In those cases the structural need is the argument, not the complexity table.

The decision rule

Default to the contiguous structure. Justify a linked list with a measurement on your workload or a specific structural requirement. Establish correctness first, make the assumption visible in the design, and reach for profiling when the decision turns on cost rather than semantics.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain doubly linked lists without using the usual slogan?

Answer

The 90-second answer

Drop the slogan and it becomes a claim about what you can do with a pointer you already hold. If I have a reference to a node in the middle of a list and I need to remove it, or move it to the front, a doubly linked list does that in constant time. A singly linked list cannot: removing that node means finding the node before it, and the only way to find it is to walk from the head, so you pay O(n) while already knowing exactly which node dies. The prev pointer buys O(1) removal and O(1) move-to-front. It costs one extra pointer per node and one extra store per splice.

Sizing it

In C on x86-64, struct node { struct node *prev, *next; void *payload; } is 24 bytes; drop prev and it is 16. A million nodes is 24 MB of links against 16 MB. On the JVM the same arithmetic comes out even. HotSpot's object header is 12 bytes with compressed oops on (8-byte mark word plus a 4-byte klass pointer, the default while the heap is under 32 GB), so prev + next + item is 12 + 12 = 24 bytes, and next + item is 20 bytes, which the 8-byte alignment rounds up to 24. Same footprint either way. On the JVM you are paying for an extra store per splice and worse locality, not for memory.

Node on 64-bitbytes
C, prev + next + payload24
C, next + payload16
Java, prev + next + item, compressed oops24
Java, next + item, compressed oops24 (20, rounded up)

The splice, traced

Every insertion or removal touches four links, and the interesting bug is that each of the four can be broken independently.

Python
# Python 3
class Node:
    def __init__(self, val):
        self.val, self.prev, self.next = val, None, None

# circular, sentinel-headed: S <-> A <-> B <-> S
def unlink(n):
    n.prev.next = n.next
    n.next.prev = n.prev
    n.prev = None
    n.next = None

Start state: S.next=A, A.prev=S, A.next=B, B.prev=A, B.next=S, S.prev=B. Call unlink(A). Line 1: A.prev is S, so S.next=B. Line 2: A.next is B, so B.prev=S. Lines 3 and 4 clear A's own pointers. Walking forward from S now yields S, B, S; walking backward yields S, B, S. Both directions agree.

Now delete line 2 and re-run the trace. S.next=B, line 1 still succeeds, and A's pointers get nulled. B.prev still points at A. Iterating forward from S yields S, B, S and looks perfectly healthy. Iterating backward from S yields B, then A, then a null dereference on the next step. The list is corrupt in exactly one direction and any forward-only test walk passes. The cheap detector is to assert the round trip after every mutation in tests, not only at the end: for each node, n.next.prev is n and n.prev.next is n.

What the sentinel is doing

With a sentinel, unlink has no branches, because every real node including the first and last has a live neighbour. Without one, the same operation needs four cases (removing the head, the tail, the only element, a middle node), and that case analysis is where hand-rolled implementations usually break. The Linux kernel's list_head (include/linux/list.h) is the sentinel version, and list_del overwrites the removed node's pointers with poison values so a stale dereference faults instead of corrupting a neighbour silently.

When it is the wrong structure

If nothing ever deletes or relocates a node you already hold, the back pointer is dead weight. A dynamic array keeps pointers in contiguous memory, one cache line per eight pointers on x86-64, against one allocation and one pointer chase per node. Java's LinkedList implements Deque, but ArrayDeque beats it as a queue or a stack for exactly that locality reason, so "I need a queue" is not a reason to reach for the linked version. The structure earns its place when a hash map hands you the node: the canonical case is an LRU cache, where the map gets you the entry in O(1) and the doubly linked list does the O(1) move-to-front. Java's LinkedHashMap with accessOrder=true is precisely this, a hash table whose entries also carry before and after pointers. If one object has to sit in several lists at once, or you cannot afford a per-node allocation, the C answer is an intrusive list: embed prev and next in the payload struct itself.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through the dummy head node, including where engineers most often get it wrong.

Answer

A dummy head (sentinel) is one extra node spliced in front of the real head so that every real node has a predecessor. Insertion and deletion collapse to one uniform splice, and the branch for affecting the first element disappears. Three parts of the contract matter: the sentinel carries no payload, it does not move during the traversal, and the function returns dummy.next whatever that is, including None when the operation empties the list.

Anchor and cursor must be two variables. dummy stays where it is; prev walks. That is the whole trick, and it keeps the splice to a single shape:

Python
class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next

def remove_all(head, target):
    dummy = Node(None, head)   # anchor: never reassigned
    prev = dummy               # cursor: walks
    while prev.next:
        if prev.next.val == target:
            prev.next = prev.next.next
        else:
            prev = prev.next
    return dummy.next          # the new head, not the sentinel and not head

Trace it on 1 -> 1 -> 2 with target = 1, calling the nodes A, B, C:

stepprevprev.nextaction
1dummyA (1)match, so dummy.next = B
2dummyB (1)match, so dummy.next = C
3dummyC (2)no match, so prev = C
4CNoneloop ends

Returning dummy.next gives C, so the result is 2. prev deliberately does not advance on steps 1 and 2, and that is exactly what a return head version gets wrong: A still points at B, which still points at C, so return head hands back 1 -> 1 -> 2 unchanged. Removing the head is the only case where the two returns differ, which is why it is the first test to write.

Where engineers get it wrong, roughly in order of how often it happens:

  1. Returning head or dummy instead of dummy.next. Returning dummy hands the caller a payload-free node; returning head hands back a node that is no longer in the list whenever the first element matched. Detection is any test where the first element matches the target, plus an assertion that the returned node is not the sentinel.
  2. Advancing the anchor. Writing while dummy.next: ... else: dummy = dummy.next reads as the familiar list-walking idiom and silently slides the anchor forward; you return a suffix, or None. Detection: a run with no matches at all over a three-element list must return all three.
  3. Exposing the sentinel. Where the head node is owned by the container rather than by the call, the sentinel is real state. Linux's intrusive list_head is the canonical case: an empty list has head.next == head, and list_for_each_entry never yields the head, because the head has no payload to hand out. A circular doubly linked sentinel also has to be wired in both directions before the first splice (dummy.next = dummy and dummy.prev = dummy), or the first back-pointer read touches an uninitialised field.
  4. Leaking it. Under manual memory management, heap-allocating the sentinel per call and returning dummy.next loses the only pointer to it. Put the sentinel on the stack, or free it after copying out its next.

When the sentinel is not worth it: it costs one allocation and a couple of pointer writes per call, so a hot loop over millions of two-element lists notices; in C or C++ placing the sentinel on the stack removes the allocation entirely. Skip it when the node could escape into the public surface, such as equality, serialisation, or an iterator whose callers expect payloads on every element. std::list in libstdc++ and libc++ keeps a hidden header node for the same uniformity, and gets away with it only because that node is never in the interface. Space is O(1) either way; time is O(n) either way.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does iterative reversal guarantee, and what does it deliberately leave open?

Answer

The 90-second answer. Iterative reversal of a singly linked list guarantees four things and is silent on the rest. It runs in Θ(n) time: exactly n iterations, each doing a constant number of pointer writes, with no data-dependent branching. It uses O(1) extra space: three pointer variables regardless of list length, no allocation and no recursion stack. It is in-place: the existing nodes are relinked, not copied, so node identity is preserved and any other reference the caller holds to those nodes stays valid. And it is a single forward pass over a singly linked list, so it needs no back pointers and never revisits a node. What it leaves open is everything about the caller's view: the function returns the new head, and whether the caller's old head variable gets updated is not the algorithm's problem.

Mechanism.

Python
def reverse(head):
    prev, node = None, head
    while node:
        nxt = node.next      # save
        node.next = prev     # redirect
        prev, node = node, nxt
    return prev

Trace on 1 -> 2 -> 3:

stepprevnodenxteffect
initNone1—1->2->3
11221.next = None
22332.next = 1
33NoneNone3.next = 2

Return 3, giving 3 -> 2 -> 1. Three iterations for three nodes; the loop body executes exactly n times.

What it deliberately leaves open.

  • Caller aliasing. The old head now points at the tail. If another variable, index, or map still holds the original head, it is stale.
  • Cycles. A list with a cycle is not detected; the loop never terminates (or reverses the cycle into a different cycle). There is no visited set and no Floyd check.
  • Concurrency. A reader running concurrently sees a partially reversed list: the structure is torn mid-loop. No lock, no atomic swap.
  • Recursion vs iteration. The guarantee is about the iterative form. The recursive form gives the same Θ(n) time but O(n) stack; in CPython the default recursion limit is 1000, so a list of a few thousand nodes raises RecursionError.
  • Order among equal keys. If nodes carry keys, equal keys come out in reverse relative order too. Reversal is not stable in that sense.

Alternatives.

approachtimeextra spacenotes
iterativeΘ(n)O(1)in-place, relinks nodes
recursiveΘ(n)O(n) stacksame relinking, stack-depth cost
explicit stack/arrayΘ(n)O(n)extra allocation
new-list head insertionΘ(n)O(n)copies nodes, not in-place

Failure mode. Redirect before saving and you lose the rest of the list. On 1 -> 2 -> 3, node.next = prev sets 1.next to None, then node = node.next reads that None, so the loop exits after one iteration and you return a single node. It survives casual testing because a two- or three-node happy path is exactly the case that hides it: trace by hand, save first.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-5

Describe recursive reversal and its cost and the evidence you would collect before relying on it.

Answer

The 60-second answer. Recursive reversal walks to the end of the list, then rewires each next pointer on the way back. It is O(n) time and O(n) stack space, one frame per node, and that space cost is the whole story. The iterative three-pointer version does the same rewiring in O(1) space. So the recursive form is only safe when you can bound the list length below the runtime's stack limit, and the evidence you need is that bound plus the runtime's actual limit.

Mechanism.

Python
import sys

def reverse(head, prev=None):
    if head is None:
        return prev
    nxt = head.next
    head.next = prev
    return reverse(nxt, head)

Trace on 1 -> 2 -> 3:

callheadprevnxtafterreturns
reverse(1, None)1None21.next = Nonereverse(2, 1)
reverse(2, 1)2132.next = 1reverse(3, 2)
reverse(3, 2)32None3.next = 2reverse(None, 3)
reverse(None, 3)None3——3

Result: 3 -> 2 -> 1. Four frames for three nodes, so n+1 frames for n nodes. Each frame holds head, prev, nxt and a return address; the byte cost per frame varies by interpreter version and build, so measure it rather than quote it.

Cost. Time O(n), space O(n) frames. The iterative version:

Python
def reverse_iter(head):
    prev = None
    while head:
        nxt = head.next
        head.next = prev
        prev, head = head, nxt
    return prev

is O(n) time, O(1) space. Same result, no stack growth.

Evidence to collect before relying on the recursive form.

  1. The runtime's actual limit. On CPython, sys.getrecursionlimit() returns 1000 by default. Reversing 10,000 nodes raises RecursionError; a few thousand will too. Confirm the number on the interpreter you deploy, not from memory.
  2. Whether the runtime eliminates tail calls. CPython, the JVM and Go do not: return reverse(...) still allocates a frame. Scheme and some functional runtimes do, which would make this O(1) space, but only because the call is in tail position. Check the language spec, not the syntax.
  3. The real list-length distribution. Pull the max and p99 from production, not the mean. If the max is 200 and bounded by a schema constraint, recursion is fine. If the length is bounded only by input size, it is not.
  4. The failure mode. RecursionError is catchable in Python; a native stack overflow in C or a JIT'd runtime is a crash. That difference decides whether you can ship it behind a guard or not at all.

Failure mode in practice. The recursive version passes casual testing because small inputs never reach the limit. The bug appears when a list arrives that is longer than every list in your test fixtures: typically from a new client, a backfill, or a data migration. Detect it by asserting a maximum length at the boundary, or by bisecting the length at which the call fails in a staging run and comparing that to the production max.

When to use which. Use the recursive form when the list length is bounded by a constant you control and the code reads more clearly. Use the iterative form when the length is bounded only by input size, or when the runtime has no tail-call elimination and no cheap way to raise the limit safely. State the space bound next to the time bound either way.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of circular lists and sentinels?

Answer

Assume the team owns a circular doubly linked list with a single sentinel, and I have their code and a test runner. The injection I run is the one that is silent on the happy path: swap the traversal terminator from the sentinel to None, and hand them a list of size 1. Everything they'd check by hand passes; the loop never returns.

Three injections, cheapest first.

1. Break the empty list. Build the sentinel with sentinel.next = sentinel.prev = None instead of pointing it at itself.

Python
class DList:
    def __init__(self):
        self.sentinel = Node()
        self.sentinel.next = self.sentinel.prev = None   # injected
        self.size = 0

    def push_back(self, val):
        s = self.sentinel
        n = Node(val)
        n.prev = s.prev
        n.next = s
        s.prev.next = n      # AttributeError: 'NoneType' has no attribute 'next'
        s.prev = n
        self.size += 1

Trace: s.prev is None, so s.prev.next raises on the first insert into an empty list. Tests whether they know the empty list is the sentinel pointing at itself, not a null. Detection is free: the first push_back crashes. Cost: one failed request, no data loss.

2. Null-terminate the traversal. The one that hangs.

Python
def __iter__(self):
    n = self.sentinel.next
    while n is not None:          # injected; correct is `while n is not self.sentinel`
        yield n.val
        n = n.next

Trace with one element: after push_back("A"), sentinel.next = A and A.next = sentinel. The loop yields "A", then n = sentinel, which is not None, so it yields sentinel.val (None), then n = A again. It yields A, None, A, None, ... forever. Tests whether they know there is no None in a circular list. Detection: a bounded iteration counter or a test timeout. list(dl) never returns, so a plain assert hangs the suite. Cost: in production this is a stuck worker, not a failed request; you find it with a watchdog or a request timeout, not a stack trace.

3. Leak the sentinel into iteration. Start the walk at the sentinel instead of sentinel.next. Trace: one element yields None, "A". An off-by-one a len() assert catches immediately. Tests whether the sentinel is kept out of the public view.

Detection harness: run all three against sizes 0, 1, 2, 3 with a timeout:

Python
def check(dl, expected):
    got = list(dl)                      # hangs on injection 2 without a timeout
    assert got == expected, (got, expected)

Sizes 0 and 1 are where the bugs live; a fuzz over 2..1000 mostly re-exercises the same two branches.

Trade-offs. The sentinel is not free:

DesignEmpty listInsert/removePer-list costTerminator
Circular + sentinels.next = s.prev = sno branches1 extra noden is not s
Null-terminated head/tailhead = tail = Nonebranch on empty, head, tail0 extra nodesn is not None
Tail pointer, no sentineltail = Nonebranch on empty1 pointern is not tail.next

A Node with three slots is ~48 bytes in CPython (16-byte header plus three pointers, allocator-rounded). At 10^6 small lists that is ~48 MB of sentinels: the reason a sentinel is the wrong call for a million tiny lists and the right call for one big one. The null-terminated version pays instead in branches: every insert and remove carries an empty-list check, and the head/tail cases are where the bugs move to.

What the injection actually tests: whether the team can say which part is a guarantee (the sentinel is always present, so no null check exists anywhere) and which part is a measurement (the extra node's cost). A team that answers "we'd add a null check" has not understood the structure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does deleting a node matter, and where is it irrelevant?

Answer

Core answer. Deletion is cheap or free exactly when two things hold: you already hold the predecessor (or the structure is doubly linked), and nothing outside the structure can observe the node's identity. Break either and deletion becomes O(n), or semantically wrong, or both. Where the structure is append-only or garbage-collected, deletion is irrelevant: you never remove a node, you stop referencing it or write a tombstone.

StructureDelete givenCostIdentity kept?
Singly linked listpredecessorO(1)yes
Singly linked listtarget onlyO(n) scan, or O(1) copy trickno (copy trick)
Doubly linked listtargetO(1)yes
Dynamic arrayindexO(n) shiftno, later indices move
Hash table, open addressingkeyO(1) amortizedno, slot reused
Balanced BSTkeyO(log n)no
Persistent treekeyO(log n) new nodesold version untouched

O(1) unlink, when you can reach the neighbours.

Python
class Node:
    __slots__ = ("val", "prev", "next")
    def __init__(self, val):
        self.val, self.prev, self.next = val, None, None

def unlink(node):
    node.prev.next = node.next
    node.next.prev = node.prev
    node.prev = node.next = None

Trace on 1 <-> 2 <-> 3, unlink(node2): node2.prev is node1, so node1.next = node3; node2.next is node3, so node3.prev = node1. List is now 1 <-> 3. Two pointer writes, no traversal, O(1). It needs node.prev to exist, so it does not apply to a singly linked list.

The copy trick, and why it is a puzzle answer.

Python
def delete_given_only(node):
    node.val = node.next.val
    node.next = node.next.next

Trace on 1 -> 2 -> 3, delete_given_only(node2): node2.val becomes 3, then node2.next = node3.next, which is None. The list reads 1 -> 3 -> None, but the object callers held as "3" is now unreachable from the list while node2 still answers to value 3. Any external reference to node3 dangles. If node2 is the tail, node.next is None and the call raises AttributeError. So the trick is O(1) but breaks identity and cannot delete the tail: fine for a whiteboard, wrong for an intrusive list, an LRU cache, or anything holding iterators.

Where deletion is irrelevant.

  • Append-only logs and event sourcing: you append a tombstone record; the original stays. Kafka log compaction keeps the last record per key, so "deletion" is a background rewrite of the log, not a pointer operation.
  • Tracing GC: you drop the reference and the collector decides. Cost is amortized into allocation, and cycles are reclaimed with no explicit delete at all.
  • Persistent/immutable structures: deleting from version N yields version N+1 with a new root; version N is untouched. That is O(log n) new nodes, not a mutation.

Where it matters.

  • Identity is observable. Intrusive lists (Linux list_head), LRU caches and live iterators all hold the node itself. The copy trick silently corrupts them.
  • Ordering is the point. LRU eviction needs O(1) unlink from the middle of a list, which is why an LRU is a hash map plus a doubly linked list, not a hash map alone.
  • Concurrent reclamation. Freeing a node another thread still holds is a use-after-free. RCU defers the free until a grace period; hazard pointers and epoch reclamation do the same. Detect it with ASan/TSan, or by a crash under load that disappears under a debugger.

Failure modes worth naming.

  • Tombstones in open-addressing hash tables. CPython's dict leaves a dummy entry on delete so probe chains stay intact, and resizes once used plus dummy entries exceed two-thirds of the table. A delete-heavy, insert-light workload still pays for the dummies.
  • Iterator invalidation. Java's ArrayList.remove inside a for-each throws ConcurrentModificationException; C++ vector::erase invalidates iterators at and after the erased position.

So: deletion is O(1) and safe when you hold the predecessor and identity is private; O(n) or unsafe when you don't; and beside the point when the structure is append-only, persistent, or garbage-collected.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How do you reverse a sublist of a singly linked list from position m to n in-place in one pass?

Answer

In 60 seconds: put a sentinel in front of the head, walk pre to position m-1, then run n-m iterations of a head-insertion splice. Each iteration plucks the node sitting after a fixed tail and re-inserts it directly behind pre. One traversal, O(1) extra space, and you never need to know what follows position n.

Mechanism

Three pointers carry the whole loop:

  1. pre: the node at m-1, fixed for the duration. The sentinel means m=1 needs no special branch.
  2. tail: the node originally at m. It never moves along the chain; it sinks deeper as nodes are plucked from in front of it, and ends up as the sublist's new tail.
  3. cur: tail.next, the node being moved this iteration.

Each iteration bridges tail.next past cur, points cur.next at the current front of the reversed run (pre.next), then points pre.next at cur. After n-m iterations the window is reversed and both ends are already wired.

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_sublist(head: ListNode, m: int, n: int) -> ListNode:
    if not head or m == n:
        return head

    dummy = ListNode(0, head)
    pre = dummy
    for _ in range(m - 1):
        pre = pre.next

    tail = pre.next
    for _ in range(n - m):
        cur = tail.next
        tail.next = cur.next
        cur.next = pre.next
        pre.next = cur

    return dummy.next

Trace: 1 -> 2 -> 3 -> 4 -> 5, m=2, n=4

pre lands on 1, tail on 2, loop runs twice.

ItercurChain after iterationWrites
131 -> 3 -> 2 -> 4 -> 52.next=4, 3.next=2, 1.next=3
241 -> 4 -> 3 -> 2 -> 52.next=5, 4.next=3, 1.next=4

Result 1 -> 4 -> 3 -> 2 -> 5. At most n nodes are visited once: O(n) time, O(1) heap and stack.

The alternative, and when it wins

The other approach, the one most candidates write from memory, is the classic three-pointer reversal applied to the window: walk to m-1, reverse the next n-m+1 nodes with prev/cur/nxt, then reconnect.

Python
def reverse_sublist_three_pointer(head, m, n):
    dummy = ListNode(0, head)
    pre = dummy
    for _ in range(m - 1):
        pre = pre.next
    cur, prev = pre.next, None
    for _ in range(n - m + 1):
        nxt = cur.next
        cur.next = prev
        prev, cur = cur, nxt
    pre.next.next = cur   # old node m is now the tail
    pre.next = prev       # old node n is now the head
    return dummy.next

Same input: after the loop prev=4, cur=5, and pre.next still points at 2, so 2.next=5 then 1.next=4 gives 1 -> 4 -> 3 -> 2 -> 5.

Both are O(n) time and O(1) space, so the deciding criteria are structural, not asymptotic. Choose the splice version when you cannot cheaply reach the node after n: it never touches it, so n = list length needs no special case, and it suits a stream where you stop as soon as you have counted n-m moves. Choose the three-pointer version when you want the identical code path as a full-list reversal (m=1, n=length is the same loop) or when the caller needs the new tail pointer returned; the price is that you must capture the node after n before severing the window, and you rewrite two links after the loop instead of three per iteration. A recursive reversal is not a candidate here: O(n) stack frames violates in-place.

Failure modes

  1. m = 1: without the sentinel, pre starts as None and pre.next raises. The sentinel also makes the return value uniform: always dummy.next.
  2. Wrong write order: setting pre.next = cur before cur.next = pre.next makes cur.next resolve to cur itself, a one-node self-cycle that silently drops every node already reversed.
  3. n past the end: tail.next becomes None, then cur.next raises AttributeError. Validate 1 <= m <= n <= length up front, or count nodes first if the length is unknown.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you detect if a linked list has a cycle using O(1) auxiliary space, and how do you locate the cycle's starting node?

Answer

Floyd's cycle-finding algorithm (the tortoise and hare) detects a cycle by advancing two pointers at different speeds (1 step and 2 steps per iteration) and finds the cycle's origin by resetting one pointer to the head after they collide and advancing both at 1 step per iteration.

1. Detection Phase

Let $L$ be the distance from the list head to the cycle start node, $C$ be the cycle length, and $k$ be the distance from the cycle start to the first collision point along the direction of traversal ($0 \le k < C$).

When the slow pointer (slow) reaches the cycle start, it has taken $L$ steps. The fast pointer (fast) has taken $2L$ steps and is at position $(L \bmod C)$ inside the cycle. The distance between them along the cycle is $(C - (L \bmod C)) \bmod C$. Because fast gains 1 step on slow in every iteration, they must collide inside the cycle within $C$ additional steps.

2. Origin Identification Phase

At the meeting point, slow has travelled $d_{\text{slow}} = L + k$ steps. fast has travelled $d_{\text{fast}} = L + k + mC$ steps for some integer $m \ge 1$. Since fast moves twice as fast as slow:

$$2(L + k) = L + k + mC \implies L + k = mC \implies L = mC - k = (m - 1)C + (C - k)$$

Notice that $(C - k)$ is the remaining distance from the meeting point to the cycle entry node. Moving $L$ steps from the meeting point along the list lands exactly on the cycle entrance.

Therefore, keeping slow at the meeting point, resetting fast to head, and advancing both one node at a time causes them to meet after exactly $L$ steps at the entry node.

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def detect_and_locate_cycle(head: ListNode | None) -> ListNode | None:
    if not head or not head.next:
        return None

    slow = head
    fast = head

    # Phase 1: Detect cycle
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            break
    else:
        return None  # Reached null; acyclic

    # Phase 2: Locate cycle start
    ptr1 = head
    ptr2 = slow
    while ptr1 is not ptr2:
        ptr1 = ptr1.next
        ptr2 = ptr2.next

    return ptr1

Complexity and Failure Modes

  • Time: $O(N)$ where $N = L + C$. Detection takes at most $L + C$ iterations; locating the start takes $L$ iterations. Total pointer steps are bounded by $3N$.
  • Space: $O(1)$ auxiliary space, needing only two pointer references.
  • Failure Modes & Edge Cases:
    • Terminating conditions: Testing only fast without checking fast.next causes an immediate AttributeError or NullPointerException on odd-length acyclic lists.
    • Single-node cycle: A node pointing to itself ($L=0, C=1$). The detection terminates immediately on step 1, ptr1 and ptr2 start identical, returning the head correctly.
    • Mutating nodes: An alternative hash set check ($O(N)$ space) or mutating nodes with sentinel flags risks concurrency hazards and invalidates read-only list semantics.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Why must the fast pointer meet the slow one, and why does moving one pointer back to the head find the cycle's entry node?

Answer

Assumption: singly linked list, nodes reachable only by following next, no length field, and nothing is mutating the list while I walk it. If it is being mutated, the answer changes: I come back to that.

In one line: the fast pointer gains exactly one position per step modulo the cycle length, so it cannot avoid the slow one; and the meeting point sits the same distance from the entry as the head does, which is why resetting one pointer to the head finds the entry.

Why they must meet. Let L be the number of edges from head to the cycle entry and C the cycle length. Once the slow pointer has entered the cycle, both pointers are on it. Slow advances 1 edge per iteration, fast 2, so the gap (fast - slow) mod C increases by 1 each iteration. A quantity that increases by 1 mod C hits 0 within C iterations. They meet within L + C steps. No coprimality assumption, no parity argument.

Where they meet. If they meet after t iterations, slow has travelled t edges and fast 2t, on the same node, so t ≡ 2t (mod C), i.e. t ≡ 0 (mod C). Write t = L + s, where s is slow's offset into the cycle. Then s ≡ -L (mod C). The meeting point is not the entry unless L ≡ 0 (mod C).

Why the reset works. Put one pointer back at the head, leave the other at the meeting point, advance both one edge at a time. After L steps the head pointer is at the entry. The other started at offset s and has moved L, so it is at s + L ≡ 0 (mod C): also the entry. They collide there, and the first collision is the entry.

Trace. Nine nodes 0…8 with 8 -> 3. Entry is node 3, so L = 3 and C = 6 (3,4,5,6,7,8).

iterationslowfast
000
112
224
336
448
554
666

t = 6, a multiple of C; s = 3 = -3 mod 6. Reset slow to 0, fast stays at 6: (1,7), (2,8), (3,3). Entry found in L = 3 steps.

Python
# CPython 3.12
def cycle_entry(head):
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            break
    else:
        return None                 # acyclic: fast ran off the end
    slow = head
    while slow is not fast:         # not do-while: L == 0 must return head
        slow = slow.next
        fast = fast.next
    return slow

The trade-off. Both are O(n) time. Floyd's is O(1) space; a visited set is O(n) space and hands you the entry node on the first repeat with no second phase. At 10^7 nodes a std::unordered_set<Node*> costs roughly 10^7 x 24 bytes of node overhead plus the bucket array, a few hundred MB, against 16 bytes for two pointers. The set also hashes and chases pointers, so its constant factor is worse. Take the set when n is small, when you already maintain a visited set for another reason, or when you need the entry node and cannot walk the list twice.

Failure modes.

  • Checking only fast is not None in the loop condition dereferences None on an even-length acyclic list. You need both checks.
  • Writing the second loop as do { ... } while (slow != fast). When the cycle includes the head (L = 0) the pointers are already equal, and a do-while advances past the entry.
  • Assuming the meeting point is the entry. It is only when L ≡ 0 (mod C).
  • Walking a list another thread is mutating. If a node the fast pointer is about to visit is unlinked, you get a null deref or an unbounded walk. Floyd's assumes a stable list; take a read lock or walk a snapshot.
  • Floyd's tells you a cycle exists, not its length. Keep the meeting point and walk one pointer until it returns: C steps.

Brent's algorithm (teleporting turtle) finds the cycle with fewer pointer advances, which matters when the walk itself is expensive, e.g. reading from a slow device.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

What are the time and space complexity trade-offs between tracking visited nodes with a hash set versus Floyd's tortoise and hare algorithm for cycle detection?

Answer

Short answer. Both are $O(N)$ time. The hash set costs $O(N)$ extra memory and hands you the cycle entrance for free; Floyd's costs $O(1)$ memory but needs a second phase to find the entrance and burns roughly three pointer dereferences per iteration. Pick the set when $N$ is small or you need the entrance; pick Floyd's when the list is large, the nodes are big, or the check runs somewhere allocation is forbidden.

Python
def has_cycle_set(head) -> bool:
    seen = set()
    cur = head
    while cur is not None:
        if cur in seen:
            return True
        seen.add(cur)
        cur = cur.next
    return False

def has_cycle_floyd(head) -> bool:
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Both are correct for plain objects, where hash/== fall back to identity.

Hash setFloyd's
Auxiliary space$O(N)$$O(1)$
Time$O(N)$ expected$O(\mu+\lambda)$ worst case
Work to detect$\mu+\lambda$ insertions, then one hit$\le \mu+\lambda$ slow steps, $\approx 3(\mu+\lambda)$ derefs
Cycle entrancereturned directlyneeds phase 2, $\mu$ more steps
Per-node costhash + bucket probe + occasional resize3 pointer derefs
Graph shapeany graphout-degree 1 only

Floyd's trace. Let $\mu$ be the acyclic prefix length and $\lambda$ the cycle length. After $t$ iterations slow sits at index $t$ and fast at $2t$.

  1. Fast enters the cycle at $t=\lceil \mu/2 \rceil$.
  2. Slow enters at $t=\mu$; fast is then at cycle position $\mu \bmod \lambda$.
  3. The forward gap from fast to slow is $g=(\lambda-\mu \bmod \lambda) \bmod \lambda$. Each iteration closes it by exactly 1 (fast gains 2, slow gains 1), so collision lands at slow step $\mu+g \le \mu+\lambda-1$.
  4. Phase 2: reset slow to head, advance both one step at a time. After $\mu$ steps slow is at the entrance, and fast has moved from cycle position $g$ to $(g+\mu) \bmod \lambda = 0$: the same node. Total work $\approx 2\mu+g$, versus $\mu+\lambda$ for the set.

Failure modes.

  • Value-based equality. A @dataclass node is unhashable by default (__hash__ is set to None when eq=True and frozen=False), so seen.add(node) raises TypeError. With frozen=True you get a field-based hash, and two distinct nodes with equal fields collapse into one entry: a list 5 -> 5 -> None reports a cycle that isn't there. Store id(node) or raw pointers if you must.
  • Memory. On 64-bit CPython a set of 1M entries allocates a $2^{21}$-slot table; each slot is a key pointer plus a cached hash (16 bytes), so the table alone is $\approx 32$ MB. A 100M-node list needs $2^{28}$ slots, $\approx 4$ GiB. If the check runs inside the leak-diagnosis path, the tool OOMs before it reports the leak.
  • Cache. Floyd's walks the list in order; the set adds a second working set (the table) that stops fitting in L2 once $N$ is large, so every step pays a bucket probe that misses.
  • Out-degree. Floyd's is meaningless on a general graph where a node has two successors; the set generalises to any traversal.

When not to use. Don't use the set on a large list inside a memory-constrained path. Don't use Floyd's if you need the entrance and $\mu$ is large (phase 2 roughly doubles the work) or if the structure isn't a functional graph. If you may mutate the list, marking visited nodes or reversing pointers gives $O(1)$ space and the entrance in one pass: at the cost of destroying the input and being unsafe under concurrent readers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you find the node where two singly linked lists intersect in O(N + M) time and O(1) auxiliary space?

Answer

Core answer (first 90 seconds)

Clarify the setup: singly linked, acyclic, and "intersect" means the two lists share a common tail. The intersection is a node identity, not a value. If either head is null, there is no intersection.

The O(1)-space trick is two pointers that switch lists. Start pA at headA and pB at headB, advancing one node per iteration. When pA falls off the end of A, redirect it to headB; when pB falls off B, redirect it to headA. Each pointer then walks the same total distance: its own list's unique prefix, the shared tail, and the other list's unique prefix, so they land on the intersection node on the same step.

Let a be the nodes unique to A before the intersection, b the nodes unique to B, and c the shared tail. Then N = a + c and M = b + c. pA walks a + c + b nodes; pB walks b + c + a. Those are equal, so they meet at the intersection. If the lists don't intersect (c = 0), both reach None after a + b steps.

Python
# Python 3.12
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def get_intersection_node(head_a: ListNode | None, head_b: ListNode | None) -> ListNode | None:
    if not head_a or not head_b:
        return None
    ptr_a, ptr_b = head_a, head_b
    while ptr_a is not ptr_b:
        ptr_a = head_b if ptr_a is None else ptr_a.next
        ptr_b = head_a if ptr_b is None else ptr_b.next
    return ptr_a  # intersection node, or None

Alternatives and trade-offs

ApproachTimeAux spaceCost
Hash set of A's nodesO(N + M)O(N)Simplest to reason about; breaks the O(1) constraint
Length-difference alignmentO(N + M)O(1)Two passes: measure N and M, advance the longer by abs(N − M), then lockstep
Two-pointer switchO(N + M)O(1)One loop, no length bookkeeping: the answer above

Hash set: walk A, insert every node into a set, then walk B and return the first node already in the set. O(N) extra memory: fine when memory is cheap, but the question rules it out.

Length-difference: measure both lengths, advance the longer list's pointer by abs(N − M), then advance both until they're equal. Also O(1) space and O(N + M) time, but it needs a separate measuring pass and explicit length arithmetic. The switch approach folds both into one loop, which is why it's the usual answer when both constraints are hard.

Worked trace

A: [1, 2] → [8, 9], B: [3] → [8, 9]. a = 2, b = 1, c = 2.

IterpApBNote
013start
128
289
39NonepB hits end
4None1pB → headA
532pA → headB
688equal: intersection

6 iterations; each pointer makes 5 node-to-node moves (a + b + c = 5). The loop runs at most N + M + 1 iterations.

Failure modes

  1. Cycles. If either list has a cycle, the pointer never reaches None, so it never redirects and the loop spins forever. Run Floyd's cycle detection on both lists first, or bound the loop at N + M + 1 iterations and return None on exhaustion.
  2. Identity vs. value. Compare node references (is in Python, == on pointers in C++/Java). Comparing .val gives false positives when independent lists hold duplicate data.
  3. Empty list. If either head is null, return None immediately: the loop would otherwise dereference null.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

How do you determine whether two singly linked lists share a common node when the lists may contain cycles, and how do you distinguish a genuine shared node from two nodes that merely hold equal values?

Answer

Start by clarifying that "share a common node" means the same node object: identity, not equal val fields. In Python that's a is b; in Java, a == b on references; in C++, pointer equality. Two nodes with val == 42 are distinct.

For acyclic lists, the standard O(N+M) O(1) two-pointer head-switching algorithm works: advance both pointers, redirect to the other head on reaching null, and compare identity. But cycles break it: lengths are undefined, and the pointers never reach null.

So detect cycles first. Use Floyd's tortoise and hare on each list. If neither has a cycle, run the standard intersection algorithm. If exactly one has a cycle, they cannot share a node: sharing any node would force the acyclic list to inherit the cycle. If both have cycles, find each cycle's entry node (second phase of Floyd). If the entry nodes are identical, the lists share the cycle and thus intersect. If they differ, traverse the cycle from one entry for one full loop; if you encounter the other entry, they share the same cycle and intersect. Otherwise they are disjoint.

Here is Python 3.12 code that returns a shared node or None:

python class ListNode: def init(self, val=0, next=None): self.val = val self.next = next

def cycle_entry(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: slow = head while slow is not fast: slow = slow.next fast = fast.next return slow return None

def shared_node(head_a, head_b): if not head_a or not head_b: return None entry_a = cycle_entry(head_a) entry_b = cycle_entry(head_b) if entry_a is None and entry_b is None: p, q = head_a, head_b while p is not q: p = p.next if p else head_b q = q.next if q else head_a return p if (entry_a is None) != (entry_b is None): return None if entry_a is entry_b: return entry_a curr = entry_a.next while curr is not entry_a: if curr is entry_b: return entry_a curr = curr.next return None

The table summarises the cases:

| Case | Action | Result | | Both acyclic | Two-pointer head-switching | O(N+M) time, O(1) space | | One cyclic, one acyclic | Cannot share | Return None | | Both cyclic | Find cycle entries; if same or reachable within cycle | Share; else disjoint |

Failure modes: using value equality gives false positives when two nodes hold the same value but are different objects. Running the standard two-pointer algorithm on cyclic lists loops forever because neither pointer ever reaches null. Computing lengths on a cyclic list is undefined and will hang. Always compare identity and detect cycles first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of splitting a list in half?

Answer

I'd refuse a design that splits a list in half in three situations. The deciding questions are whether the split mutates structure the design doesn't own, whether the walk is guaranteed to terminate, and whether the split earns its cost.

Aliased nodes. The midpoint split works by severing: the node before the slow pointer gets next = None. That mutates a node, not a list object. If any other component holds a reference to the head or to an interior node, the split silently truncates what they see. If the list is shared (a cache, a queue another thread drains, a node reused in two structures) I refuse the destructive split and either copy or return the two heads without severing, documenting that they share a suffix.

Circular input. Fast/slow relies on fast reaching None. On a circular list it never does; the loop spins forever. If the input can be cyclic, refuse unless the design bounds the walk with a known length or runs cycle detection first.

Cost. If the split exists only to feed a merge sort, refuse it. Top-down merge sort scans to the midpoint at every level: about n·log₂n extra pointer steps. For n = 1,000,000 that's roughly 2×10⁷ steps spent finding midpoints that bottom-up merge sort never takes: bottom-up is O(n log n) merges and zero split scans.

Then the mechanics, briefly, because a refusal has to be precise about what breaks.

Python
def split(head):
    slow, fast, prev = head, head, None
    while fast and fast.next:
        prev, slow, fast = slow, slow.next, fast.next.next
    if prev is not None:
        prev.next = None
    return head, slow

Trace on 1→2→3→4: slow=1, fast=1, prev=None. Iteration one: prev=1, slow=2, fast=3. Iteration two: prev=2, slow=3, fast=None. Exit; prev.next = None cuts 2→3. Halves are [1,2] and [3,4]. On 1→2: one iteration sets prev=1, slow=2, fast=None; the cut gives [1] and [2]. On a single node 1: the loop body never runs, prev stays None, and the function returns (1, 1). Head and slow are the same node. That's the aliasing hazard in miniature: the "two halves" are one list.

Refuse whenWhyInstead
Nodes aliased or list sharedprev.next = None mutates a node others holdcopy, or return halves without severing
Input may be circularfast never reaches None; loop never endsbound by length, or detect the cycle first
Split feeds a sortn·log₂n extra steps to find midpointsbottom-up merge sort
n == 1head and slow are the same nodehandle explicitly
Boundary is semanticcount-based halving ignores meaningsplit on the key

Failure mode to name: a split that skips the sever leaves both halves sharing a suffix, so the recursion never terminates or elements duplicate. It survives a check that only confirms split returned two non-null heads; it shows up as non-termination, which is why the single-element and two-element cases are the ones to test.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does merging two sorted lists change if the workload grows by two orders of magnitude?

Answer

The 60-second answer. The asymptotics don't change: merging two sorted lists is O(n) time and, if you splice, O(1) extra space at any size. What changes at 100x is which cost dominates. For a linked list the per-element cost is a pointer chase, so once the nodes stop fitting in cache the constant jumps roughly 20x and 100x data costs closer to 2000x time. For contiguous arrays the access stays sequential and prefetchable, so 100x data costs roughly 100x time. And if 100x pushes the data out of RAM, the algorithm changes class: in-memory two-way merge becomes an external k-way merge that is I/O bound, not comparison bound.

Illustrative figures on a typical x86 server (L2 1 MB, L3 32 MB, DRAM ~90 ns), merging two lists of equal size:

2×10⁴ nodes (baseline)2×10⁶ nodes (100×)
linked-list splice, 32 B/node640 KB, fits L2, ~4 ns/step → ~80 µs64 MB, DRAM, ~90 ns/step → ~180 ms
array merge, 8 B/elem160 KB, L2, ~0.5 ns/elem → ~10 µs16 MB, L3/DRAM but sequential → ~3 ms

The list version is ~8x faster at the baseline and ~60x slower at 100x. Same algorithm, same O(n); the memory hierarchy decides.

The splice, iteratively.

Python
class Node:
    __slots__ = ("val", "next")
    def __init__(self, val, nxt=None):
        self.val, self.next = val, nxt

def merge(a, b):
    dummy = tail = Node(None)
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b          # attach the remainder wholesale
    return dummy.next

Trace on a = 1→3, b = 2→4: 1<=2 → attach 1, a=3; 3<=2 false → attach 2, b=4; 3<=4 → attach 3, a=None; loop exits, tail.next = b attaches 4. Result 1→2→3→4. The remainder is attached in one pointer write, not looped over: that is what keeps the tail of the merge O(1).

Failure modes and how to detect them.

  • Splice destroys the inputs. After the merge, a and b are consumed; a caller still holding list A's head now sees a suffix. Detect: assert both inputs are None post-merge, and add a test that merging the same two lists twice fails loudly instead of silently returning a short list.
  • Recursive merge blows the stack at scale. CPython's default recursion limit is 1000; even raised, 2M frames at ~100 B each is ~200 MB. Detect: RecursionError around 10⁵ depth. Use the iterative loop above.
  • The cache cliff is invisible to unit tests. Detect: perf stat -e cache-misses,cache-references on 10⁴ vs 10⁶ inputs; ns/element stays flat for arrays and climbs for lists.
  • Sentinel with None values. If val can be None, a.val <= b.val raises TypeError on the first step. Detect: comparison error immediately, not a wrong order.

Trade-offs. Splice is O(1) space and allocation-free but mutates inputs and is cache-hostile; copying into an array costs O(n) space but is sequential and ~20x faster per element at 10⁶. Splice when the nodes already exist and you are merging runs (bottom-up merge sort on a list); copy when you control layout. With k sorted runs, a heap gives O(n log k): at k=64 that is 6 extra comparisons per element, cheaper than k−1 sequential passes. Past RAM, stream both inputs and write output; cost is I/O (64 MB at 500 MB/s NVMe ≈ 128 ms), not comparisons. Don't splice if the caller needs the inputs intact.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

A vendor promises merge sort on a linked list is handled for you. What do you still own?

Answer

What you still own

Assume the vendor's sort is a correct, stable, O(n log n) merge. That assumption is the whole point: the algorithm is theirs, the contract it runs under is yours. Four things stay on your side of the line: the comparator's total-order guarantee, whether stability is actually required, the allocation and GC cost of how they implemented it, and the constant factors on your data. None of those live in the library.

You ownWhy the vendor can'tHow it fails
Comparator is a total orderThe library trusts whatever you passJava throws IllegalArgumentException: Comparison method violates its general contract!
StabilityA merge is stable only if ties take the left runEqual keys silently reorder
Allocation / GCDepends on their implementation, not the algorithmTransient array or node churn → GC pause
Constant factorsDepends on your access patternPointer chasing, several times slower than an array sort

Comparator and stability, in code (Java 17):

Java
record Order(long id, long ts) {}

// Total order: ties broken by id, so the comparator is consistent and transitive.
Comparator<Order> byTs =
    Comparator.comparingLong(Order::ts).thenComparingLong(Order::id);

// If equal ts values must keep insertion order, do NOT add the id tiebreak —
// that replaces stability with a deterministic order you now have to defend.

A comparator that reads a mutable field, or returns inconsistent results for the same pair, is not a total order. Java's Timsort only validates the contract once a run grows past 32 elements, so a 20-element unit test passes and production throws. Test with a few thousand elements and duplicate keys, not a toy list.

Stability is a separate test: build a list with duplicate keys, sort it, and assert the original relative order survived. If it didn't, the vendor's merge takes from the right run on ties.

The arithmetic you should be able to defend (illustrative, 10M nodes):

  • Java's List.sort default copies to an array first: 10M references is an 80 MB transient allocation, a young-gen promotion risk on a latency-sensitive path.
  • Each merge step follows a next pointer. A DRAM miss is ~80–100 ns against ~1 ns for an L1 hit. Sorting 10M nodes touches each node about log2(10M) ≈ 23 times, so ~230M dereferences; even a 10% miss rate is roughly 1.8 s of stall.

Failure modes and detection

  • Contract violation: intermittent IllegalArgumentException under load. Detect with a property test over random comparators, or run once with -Djava.util.Arrays.useLegacyMergeSort=true and diff the output.
  • Unstable merge: silent reordering of equal keys. Detect with the duplicate-key assertion above.
  • Allocation spike: GC pause on the sort path. Detect with allocation profiling and GC logs, not with a wall-clock benchmark that hides it.
  • Cache-hostile pointer chasing: 2–5x slower than sorting a contiguous array. Detect by benchmarking your real data, not a synthetic list of ints.

When not to use it

If you don't need node identity preserved, copy to a contiguous array and sort: Java's Collections.sort and List.sort already do exactly that for a LinkedList, and it usually wins despite the copy. Reach for an in-place linked-list merge (std::list::sort in C++ is stable and splices without allocating) only when iterators or pointers into the list must stay valid across the sort. That is the one guarantee the array copy cannot give you, and it is the reason to pay the constant-factor cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does unrolled lists and deques force that a junior answer usually skips?

Answer

The trade-off is indexing versus ends: you can have O(1) push/pop at both ends, or O(1) random access, but an unrolled list that keeps only head and tail pointers gives up the second. A junior answer stops at "deque is O(1) at both ends" and treats it as a strict upgrade over a list. The cost lands on the read path.

Mechanism. CPython's collections.deque is a doubly-linked list of blocks, each block a contiguous array of 64 PyObject* pointers (BLOCKLEN = 64 in _collectionsmodule.c). Push and pop at either end touch the first or last block: O(1) amortized, with a new block allocated only when the end block fills. Iteration walks a block's 64 pointers sequentially (512 bytes, eight 64-byte cache lines) so you take about one cache miss per 8 elements instead of one per element for a node-per-element list. That is the locality you buy.

Indexing is what you sell. d[i] has no arithmetic address, because the deque stores only leftblock and rightblock. CPython walks from whichever end is closer, following block links until it reaches block i // 64, then reads offset i % 64. Each link is a dependent load: the next block's address isn't known until the previous load returns, so the loads serialize and the prefetcher can't help.

Trace d[500_000] on a 1,000,000-element deque. 500_000 // 64 = 7812, 500_000 % 64 = 32. Since 500_000 >= len >> 1, CPython takes the right-hand branch: n = (999_999 - 500_000) // 64 = 7812 hops back from rightblock, then reads offset rightindex - 31 = 63 - 31 = 32 of block 7812. That is 7812 dependent pointer loads for one element. The same index on a list is one multiply and one load: base + 500_000 * 8.

The trade-off is a design choice, not a law. C++ std::deque in libstdc++ and libc++ is also a chunked structure, but it keeps a separate array of chunk pointers, so operator[] is arithmetic on that map: O(1) indexing, at the cost of one extra indirection and a map that must be maintained. Java's ArrayDeque is a circular array: contiguous, O(1) both ends amortized, and indexable in O(1) internally even though Deque doesn't expose get(int). CPython chose head/tail pointers and no map, which is why its indexing walks.

StructureIndexPush/pop endsIteration locality
list (array)O(1)O(n) front, O(1) amortized backbest: contiguous
CPython deque (unrolled, no map)O(n)O(1) both~1 miss per 8 elements
C++ std::deque (unrolled + chunk map)O(1)O(1) both~1 miss per 8 elements
node-per-element linked listO(n)O(1) both1 miss per element, +8 bytes/node
ring buffer, fixed capO(1)O(1) bothcontiguous

Deciding criterion: if the workload indexes, use a list or a ring buffer. If it pushes and pops both ends and rarely indexes, use a deque. If you need O(1) indexing and O(1) both ends, a ring buffer of known maximum size gives both; the deque only wins when the size is unbounded.

Failure mode. Indexing a deque in a loop. for i in range(len(d)): d[i] is O(n²): the hops sum to roughly (n²/4)/64 ≈ 4×10^9 dependent loads at n = 10^6, which at ~100 ns per dependent load is minutes of wall time where a list takes milliseconds. Detect it by profiling, the time lands in the deque index walk, and fix it with for x in d (O(n) iteration) or by converting to a list once. Small deques and end-only access never touch the walk, which is why the cost survives casual testing.

So: the trade-off is indexing for ends. Name it before reaching for a deque.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is memory overhead per element?

Answer

The 90-second version

Before I read the diff I need three numbers: the element type, the element count per collection, and how many collections are live at once. "Memory overhead per element" is only reviewable against a budget: without the count, a per-element cost is unbounded.

Then I read the diff for the one change that adds per-element cost: an array becoming a linked list, a primitive becoming a boxed type, a new field on a per-element struct, or each element wrapped in a map entry. I compute the delta per element from the diff, multiply by the count, and compare to the budget. If the count is data-dependent, I ask for a measurement instead of accepting an argument.

Merge criteria: merge if the delta is bounded and inside budget; request changes if it grows with the count or blows the budget; ask for a retained-size benchmark when the count is unknown.

Reading the diff

The shape matters more than the constant. A per-collection header (a 56-byte list object) is noise. A per-element cost multiplies by the count, so that is where I look.

RepresentationPer-elementvs baseline
Java int[]4 Bbaseline
Java ArrayList<Integer>4 B ref + 16 B Integer = 20 B5×
Java linked node, 2 refs12 B header + 8 B refs → 24 B padded6×
Python list of ints8 B pointer + 28 B int = 36 B—
Java HashMap entry12 B header + hash + key + value + next ref → 32 B padded—

The trap is counting the container and forgetting the elements. A Python list(range(1_000_000)) is not 8 MB. The pointer array is 8,000,056 bytes, but each int is a separate 28-byte object, so the retained size is ~36 MB. Reviewing the container alone understates it by 4.5×.

Python
import tracemalloc
tracemalloc.start()
xs = list(range(1_000_000))
print(tracemalloc.get_traced_memory()[0])  # ~36 MB = 8 MB pointers + 28 MB ints

What I ask for in the PR

A retained-size number, not a wall-clock one. A change can be faster and still exhaust the heap. In Java that is a heap dump with retained size (MAT) or jcmd <pid> GC.class_histogram; in Python, tracemalloc, or sys.getsizeof on the container plus the per-element objects. I want the measurement at the real element count, because fixed costs hide per-element ones at small N.

Failure modes I check for

  • Container-only sizing: the 8 MB vs 36 MB mistake.
  • Wall-clock benchmarks standing in for memory.
  • A benchmark at 1k elements when production holds 10M.
  • Assuming the JIT unboxes a collection: it does not; ArrayList<Integer> keeps the objects.
  • Ignoring lifetime: a transient per-element allocation is cheap (young gen), a long-lived retained set is not. The same delta is a different risk depending on how long the collection lives.

Decision

Merge when the delta is bounded, inside budget, and documented. Request changes when it grows with the count and the budget is unknown or exceeded. Ask for a benchmark when the count is data-dependent: that is the case the review cannot settle by reading.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about in-place versus copying?

Answer

I default to copying: it keeps the caller's data intact and removes aliasing as a class of bug. The smallest experiment that would flip me is a two-arm benchmark on the real element type at the real N, each arm in its own process, measuring p99 wall time, peak RSS, and one hardware counter. The falsifier is stated before I run it: if in-place is under 1.3x faster at p99 and the copy arm's peak RSS stays under half the container limit, I keep copying. If in-place is 2x+ faster, or the copy arm trips the memory limit, I switch.

Python
# numpy 1.26, CPython 3.12. Run as: python bench.py in_place | copy
import numpy as np, time, resource, sys

N = 10_000_000
base = np.random.default_rng(0).random(N)   # float64, 80 MB

def arm_in_place():
    t0 = time.perf_counter()
    base += 1.0          # mutates in place; values drift across iterations, timing does not
    return time.perf_counter() - t0

def arm_copy():
    t0 = time.perf_counter()
    b = base + 1.0       # allocates 80 MB, then writes it
    return time.perf_counter() - t0

arm = {"in_place": arm_in_place, "copy": arm_copy}[sys.argv[1]]
for _ in range(3): arm()
ts = sorted(arm() for _ in range(50))
print(f"p50={ts[25]*1e3:.1f}ms p99={ts[49]*1e3:.1f}ms "
      f"peak_rss={resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024:.0f}MB")

Run each arm under perf stat -e minor-faults,cycles as well. Wall time alone tells you that copying costs more; the counter tells you why, and the why decides the fix.

Hypothetical numbers for this shape of workload, to show what the output looks like:

armp50p99peak RSSminor faults/call
in-place38 ms44 ms82 MB~0
copy71 ms96 ms163 MB~20,500

The 33 ms gap decomposes: 80 MB read plus 80 MB written at ~10 GB/s is ~16 ms of extra memory traffic; 80 MB / 4 KiB = 20,480 pages faulted in at ~0.3 µs each is ~6 ms; the rest is the allocator's mmap/munmap pair, since 80 MB is far above glibc's 128 KB MMAP_THRESHOLD, so every call gets a fresh mapping rather than a recycled heap block.

What actually changes my mind, in order of how often it happens:

  1. Someone still holds the input. A cache, another thread, or a caller that reuses the buffer after the call. Then in-place is wrong regardless of the numbers and the benchmark is moot: check this first, it is a grep, not an experiment.
  2. The copy arm crosses the cgroup limit. Compare ru_maxrss against /sys/fs/cgroup/memory.max. The failure is an OOM kill, not a slow path, so a latency-only benchmark misses it entirely.
  3. N relative to cache. At 256 KB the array sits in L2 and the copy arm will come in under 10% slower: keep copying. At 80 MB against a 32 MB L3 the extra traffic is unavoidable and in-place wins. This is why the experiment must run at the real N; a toy N answers a different question.

Failure modes to watch while running it. In-place on a numpy view (a[::2] += 1) mutates the base array: detect with a.base is not None. In-place while another thread reads gives torn reads, not exceptions: detect with TSAN or an ownership assertion. And a warm allocator hides the mmap cost, which is why each arm gets a fresh process.

If the copy arm's cost turns out to be dominated by page faults rather than memcpy, the answer is neither option: copy into a preallocated scratch buffer you reuse across calls. That is the outcome most likely to change my mind, and it is invisible to a wall-clock-only benchmark.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why recursion over lists delays a ship date?

Answer

I'd open with the decision, not the mechanism. Product needs the date, the cause in one sentence, and the options before they need to know what a stack frame is.

The 90-second version

"Ship date moves from Thursday to Monday. The cause is one function: our event serializer walks a linked list by calling itself once per item, and Python stops that at 1,000 nested calls. Staging lists top out around 40 items; a customer's import this week had 12,000. The fix is rewriting that one function as a loop: a day to write, a day to test. If Thursday is immovable I can ship a guard that rejects lists over 1,000, but that turns a crash into a rejected import. I recommend Monday."

That's the whole briefing. Everything after it is answering their questions.

Why it's a delay and not a bug fix

The recursive version is correct for every input it can finish. It fails at a boundary, not on a logic error, so there's no small patch: the shape of the function has to change. A loop over the same list uses one frame regardless of length:

Python
# recursive version: one stack frame per node, depth == len(list)
# iterative fix: constant stack, same O(n) time
def walk(node):
    while node:
        yield node
        node = node.next

Same time complexity, O(n). The difference is space: O(n) stack versus O(1).

The options, with numbers

OptionWorkShipsWhat product gets
Ship as-isnoneThursdaycrashes on any list > 1,000
Guard + clear errorhalf a dayThursdayrejects valid imports > 1,000
Iterative rewrite2 daysMondayno known limit

I'd bring that table rather than adjectives. "Doesn't scale" invites a debate about scale; "fails above 1,000 items, customer data hit 12,000" ends it.

What I'd commit to

Monday, and I'd say why the estimate is two days and not one: the rewrite is small, but the test that matters is a list longer than anything in staging, and building that fixture is the second day. If they push for Thursday, the guard is the honest stopgap: it fails loudly and tells the customer which import to split, instead of a 500.

The one thing I wouldn't do is promise Thursday and quietly ship the recursion. The failure is input-dependent, so it survives a demo and surfaces in a customer's account, which costs more than the two days.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does testing pointer manipulation interact with rollback, and where do people ignore that?

Answer

Assumption first: "rollback" here means undoing an in-place pointer mutation when the operation aborts (a transaction abort, a failed allocation, a failed compare-and-swap) not git revert. If the interviewer means something else, say so in the first sentence; the rest of the answer changes.

The interaction. The tests that catch link-manipulation bugs and the tests that catch rollback bugs are the same tests, run at the same sizes. Link bugs cluster at length 0, 1, 2 and at head/tail because those are the cases where a sentinel is absent, a neighbour pointer is null, or an off-by-one gap opens. The undo path has its own head/tail/empty cases, and they are not the same cases as the forward path's. A rollback that restores head correctly on a non-empty list can still leave tail stale on a one-element list. So the two halves have to be asserted together, on the same boundary inputs, or each hides the other's bug.

Where it's ignored. The usual test asserts the forward traversal equals the pre-state. That passes with a stale back-pointer, because forward traversal never reads prev. Concrete case: a doubly linked list with a two-node insert that rolls back the first node when the second allocation fails:

Python
class Node:
    __slots__ = ("val", "prev", "next")
    def __init__(self, val):
        self.val, self.prev, self.next = val, None, None

class List:
    def __init__(self):
        self.head = self.tail = None
        self.size = 0

    def link_after(self, prev, node):        # prev=None means at head
        nxt = prev.next if prev else self.head
        node.prev, node.next = prev, nxt
        if prev: prev.next = node
        else:    self.head = node
        if nxt:  nxt.prev = node
        else:    self.tail = node
        self.size += 1

    def unlink(self, node):                  # correct
        if node.prev: node.prev.next = node.next
        else:         self.head = node.next
        if node.next: node.next.prev = node.prev
        else:         self.tail = node.prev
        self.size -= 1

    def unlink_buggy(self, node):            # missing tail restore
        if node.prev: node.prev.next = node.next
        else:         self.head = node.next
        if node.next: node.next.prev = node.prev
        self.size -= 1

def insert_pair(lst, a, b, alloc):
    n1 = alloc(a)
    lst.link_after(lst.tail, n1)
    try:
        n2 = alloc(b)
    except MemoryError:
        lst.unlink(n1)          # swap for unlink_buggy to see the failure
        return False
    lst.link_after(n1, n2)
    return True

Trace on pre = [1] with unlink_buggy: build gives head = tail = N1, size = 1. alloc(9) returns n1; link_after(N1, n1) sets nxt = N1.next = None, n1.prev = N1, n1.next = None, then N1.next = n1 and tail = n1, size = 2. alloc(10) raises; unlink_buggy(n1) sets N1.next = n1.next = None, and because n1.next is None the missing else leaves tail = n1, size = 1. Forward from head: N1 -> None gives [1]. The test passes. Backward from tail = n1: 9 -> N1 -> None gives [9, 1], expected [1]. Fails. That is the ignored case: rollback is verified in one direction only, and only on lists long enough that the tail branch is never the one taken.

Trade-offs. Full snapshot comparison on every abort is O(n) per rollback and O(n²) across a test that aborts at every position: fine for a unit test, too slow folded into a fuzz loop over 10⁶ operations. Alternatives: (a) assert only the touched neighbourhood (node, its two neighbours, head, tail, size). O(1), catches the stale-tail bug above, misses corruption two hops away; (b) use a persistent/copy-on-write structure so rollback is "drop the new root" and there is nothing to undo. Removes the bug class, costs an allocation per mutation; (c) an undo log with an inverse operation per mutation, replayed in reverse. O(k) for k mutations, but the inverse operations are themselves pointer code needing the same boundary tests. Pick (a) for hot fuzz loops, (b) when mutation rate is low and the allocation is affordable, (c) when a WAL already exists for durability.

When not to bother: if the structure is rebuilt from a log on abort rather than mutated in place, there is no rollback pointer code to test. Test the replay instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names the LRU cache structure as the cause?

Answer

What a strong candidate says first

An alert that names a data structure is reporting which component emitted the signal, not what broke. The LRU cache is a suspect, not a verdict. On-call's first five minutes answer two questions in order: is there real user impact, and is the cache the cause or a victim of something upstream.

Confirm impact from the SLI, not the cache metric. If p99 latency and error rate are flat, the alert is noise: a cache metric moved without touching users, so downgrade it and move on. If users are affected, pull three cache signals: hit rate, eviction rate, and cache size against its configured max.

Then the fork:

SignalCache is the causeCache is a victim
Hit ratedropped, evictions spikingdropped, evictions flat
Cache sizepinned at maxbelow max
Backing store latencynormalelevated
Recent deploykey format or TTL changedunrelated

Hit rate down, evictions spiking, cache pinned at max: the working set outgrew the cache. Hit rate down, evictions flat, backing store slow: the cache is fine. The store got slow, entries expire before reuse, and the cache is just reporting it.

Worked example (hypothetical figures)

A service at 10,000 QPS with a 95% hit rate sends 500 requests/s to the backing store. Hit rate drops to 60% and misses become 4,000/s: an 8x load increase on the store. That saturates a store sized for 500/s, which slows, which lowers the hit rate further because entries expire before reuse. The cache alert is the first symptom of a feedback loop, not its origin.

Failure modes and how to detect them

  • Eviction storm from an undersized cache: eviction rate climbs while hit rate falls, cache size pinned at max. Fix by raising the size limit if memory allows, or sharding the cache.
  • Key-space change from a deploy: hit rate collapses toward zero right after a release because every key is new. Detect by correlating the hit-rate drop with the deploy timestamp; mitigate by rolling back.
  • Scan pollution: a batch job or a KEYS-style scan walks the whole key space and evicts the hot set. Hit rate drops during the job and recovers after; detect by correlating with batch schedules.
  • Lock contention on the recency list: under high concurrency the move-to-front on a shared list serialises. Detect via lock wait time or CPU spent inside the cache, not via hit rate.

Trade-offs

LRU is the default because it is cheap and good for recency-skewed access. It is the wrong choice for scan-heavy or frequency-skewed workloads: LFU or a segmented LRU resists scan pollution. Redis does not implement exact LRU: it approximates it by sampling maxmemory-samples keys (default 5) and evicting the oldest sampled, and its default maxmemory-policy is noeviction, so a cache that "should" evict will instead start rejecting writes. Check the policy before assuming eviction is happening.

Mitigation

If the cache is the cause and users are hurt, the fastest safe move is usually to raise the size limit or roll back the deploy that changed the key space. Disabling the cache is a last resort: it removes the failure but sends full load to the backing store. Exactly the 8x spike above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on intrusive lists, and what does not?

Answer

A runbook section on intrusive lists is not a page about linked lists. It exists so whoever gets paged at 03:00 can tell, in one read, whether the crash in front of them is a membership violation, and what to type next. Everything else is cut.

Assumptions for the version below: C or C++ on a 64-bit target, a struct list_head-style hook of two pointers (16 bytes per link set), debug builds with assertions on, production builds without.

What belongs

The invariant, one line, because it is the only thing that ever gets violated: one link set means at most one container. The bytes behind next/prev belong to whichever container the object is currently in, and nothing outside that container may write them.

Then a symptom table where every row ends in a check you can run from a shell:

SymptomCauseCheck
Hard lockup, RCU stall, or a worker pinned at 100% CPU walking a list that holds two or three elementsThe node was added twice to the same list, so its next became a self-loopReboot with CONFIG_DEBUG_LIST=y; `dmesg
Page fault at a LIST_POISON address (0x100 or 0x122 on the generic config, shifted by POISON_POINTER_DELTA when CONFIG_ILLEGAL_POINTER_VALUE is set)A walk touched a node after list_del wrote the poison values into its linksFind the list_for_each_entry whose body unlinks; it needs list_for_each_entry_safe
KASAN use-after-free inside a walk, none at the free siteThe node's lifetime ended while it was still linkedWho unlinks on destruction - RAII in C++, Drop in Rust, an explicit teardown in C

Then the knob that decides which of those you actually see. CONFIG_DEBUG_LIST turns the double-add into a one-line panic; with it off, production gets the cycle instead. Boost.Intrusive's default safe_link mode asserts on the same class of mistake, while auto_unlink trades a larger hook for O(1) unlink when you do not have the container in hand. Rust's intrusive-collections crate will not catch it: the container holds non-owning references and checks nothing at runtime. Windows' LIST_ENTRY plus CONTAINING_RECORD has the same shape and the same exposure.

Then recovery: which lock to take, and how to drain a corrupt list without walking into the cycle.

The trace that makes row 1 checkable

C
/* Head H, node A already linked: H<->A<->H. Add A a second time: */
list_add(&A.link, &H);

/* __list_add(new=A, prev=H, next=H->next) performs four writes: */
next->prev = new;   /* A.prev = A  */
new->next  = next;  /* A.next = A  */
new->prev  = prev;  /* A.prev = H  */
prev->next = new;   /* H.next  = A */

Held state: H.next = A, H.prev = A, A.next = A, A.prev = H. Because A.next points at A, a forward walk from H visits A, then A, then A, and never returns to H. The list contains one element and the walk does not terminate. No validity check ran, because the debug build is not the one that crashed.

What does not belong

  • The API surface: whether to call list_add or list_add_tail, how iterators are spelled. That is the header's own documentation, one jump away.
  • Design rationale and benchmarks. "Intrusive beats std::list because it removes one allocation per insertion, and three memberships cost 48 bytes inside the object instead of three separately allocated nodes" is true, and it belongs in the ADR next to the criteria that settled it: does the object ever need to be in two containers, is it copied or moved, does its lifetime outlive the membership, and would a pool- or slab-backed std::list have removed the malloc without coupling object lifetime to membership. If any of those answers is yes, intrusive was the wrong structure. Stale numbers in a runbook get read as current.
  • Warnings with no check attached. "Be careful with lifetimes" is not actionable; dmesg | grep -E 'list_(add|del) (double add|corruption)' is.
  • Anything specific to one service's invariants. The section is about the data structure; the service's own rules go with the service.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document choosing the structure so the next owner can operate it?

Answer

The deliverable is an ADR that names the one operation the structure exists to serve, the alternative you rejected, and the invariant that breaks if someone swaps it. The next owner operates the system by knowing which operation is load-bearing and which is incidental: everything else in the document is supporting detail.

Why the operation is the thing to record: a structure is only "right" relative to an access pattern. A contiguous array wins because one 64-byte cache line delivers eight 8-byte pointers to the prefetcher, so iteration is memory-bandwidth-bound. A linked list loses that and pays a dependent load per hop; if nodes are scattered, each hop is a likely DRAM access at roughly 80-100 ns versus an L1 hit near 1 ns. That gap is the whole argument, and it only exists because of the operation you are optimizing.

Arithmetic that makes it checkable: iterating 1M elements in a contiguous array touches 1M x 8 B = 8 MB of pointers. The same 1M elements as separately allocated nodes touch 1M distinct 64-byte cache lines = 64 MB of memory traffic, and each hop depends on the previous load, so the prefetcher cannot hide it. Same big-O, roughly 8x the traffic and no overlap.

The ADR skeleton:

MARKDOWN
# ADR-014: order book uses a doubly linked list plus an id index

Status: accepted

Context
  cancel-by-id runs ~40k/s and names an order id.
  Full iteration happens only on snapshot, ~1/s.

Decision
  Orders live in a doubly linked list; id -> node lives in a dict.
  Cancel is O(1): dict lookup, then unlink the held node.

Consequences
  - Replacing the list with an array makes cancel O(n). Don't.
  - Dropping the dict makes cancel an O(n) scan. Don't.
  - Snapshot iteration is pointer-chasing; fine at 1/s.
  - If cancel drops below ~100/s, an array is simpler - revisit.

(Those figures are an illustrative example, not a benchmark.)

The table the Context section is drawn from:

Dominant operationStructureMechanism
Index, iterate, memory-boundcontiguous array (list)one cache line feeds 8 pointers; prefetcher runs ahead
push/pop at both endsdequeCPython: doubly linked list of 64-pointer blocks; O(1) ends, no realloc
Reorder a node you already holddoubly linked list + id-to-node indexunlink is a few pointer writes, no shifting
Keyed lookuphash table (dict)open addressing, O(1) average

Failure modes, and how you catch them:

  • The ADR records the decision but not the operation. The next owner cannot tell what is safe to change. Test: ask "which operation breaks if I swap this?" If the document cannot answer, it is incomplete.
  • No rejected alternative. The reader re-litigates the choice in review. Name the array you did not pick and why.
  • No test pinning the invariant. The decision rots silently when someone "simplifies" the list into an array. Add a test that cancels by id at the expected rate and asserts flat latency, so the swap fails CI instead of production.

Handover is the ADR plus that test. The document says why; the test keeps it true.

Curated: · Written: · Reviewed:

Difficulty: Medium