Linked Lists
- Manipulate singly linked lists in Go without losing nodes: dummy heads, three-pointer reversal, splitting and weaving
- Use fast/slow pointers to find the middle, the k-th from the end, and the entrance of a cycle — and prove why Floyd's algorithm works
- Build an O(1) LRU cache from a hash map and a doubly linked list, generically, and know when not to use LRU
- Explain why linked lists are rare in high-performance Go code, and where they still win
TL;DR
- Dummy (sentinel) head removes every "what if I delete the head?" special case. Return
dummy.Next. - Reversal:
next := curr.Next; curr.Next = prev; prev, curr = curr, next— savenextbefore you rewire. - Fast/slow pointers: fast moves 2, slow moves 1. Middle when fast ends; meeting means a cycle; reset one pointer to head and step both by 1 to find the cycle entrance.
- Gap pointers find the k-th node from the end in one pass.
- LRU cache = map (key → node) + doubly linked list (recency order). Get and Put are O(1); evict from the tail.
- In production Go, slices usually beat lists (cache locality, fewer allocations, less GC work). Lists win when you need O(1) removal given a handle — LRU, free lists, intrusive queues.
When to reach for it
- The input is a
ListNode— the interview is about pointer discipline more than algorithms. - "In one pass", "O(1) extra space" on a list → fast/slow or gap pointers.
- "Cycle", "loop", "duplicate number in 1..n with O(1) space" (an implicit linked list via
next = nums[i]) → Floyd. - "Merge sorted lists/streams" → dummy tail, then a heap for k lists (Heaps & Priority Queues).
- "Design a cache with O(1) get/put and eviction" → map + doubly linked list.
- You hold a pointer to an element and must remove or move it in O(1) → doubly linked list.
Core concepts
Node type and the dummy head
type ListNode struct {
Val int
Next *ListNode
}
// mergeTwoLists merges two sorted lists by relinking nodes (LeetCode 21).
func mergeTwoLists(a, b *ListNode) *ListNode {
dummy := &ListNode{}
tail := dummy
for a != nil && b != nil {
if a.Val <= b.Val { // <= keeps the merge stable
tail.Next, a = a, a.Next
} else {
tail.Next, b = b, b.Next
}
tail = tail.Next
}
if a != nil {
tail.Next = a
} else {
tail.Next = b
}
return dummy.Next
}
The dummy means the first real node is attached exactly like every other node — no if head == nil branch. Merging is O(n + m) time and O(1) extra space because it relinks existing nodes.
Reversal
Three pointers: prev (reversed prefix), curr (next node to move), next (saved so the rest of the list is not lost).
Mid-way through reversing 1 → 2 → 3 → 4: the reversed prefix hangs off prev, the untouched suffix off curr. Each step moves one node from the second chain to the front of the first.
Fast and slow pointers
- Middle: when fast reaches the end, slow is at the middle. With
for fast != nil && fast.Next != nil, slow lands on the second middle for even lengths; withfor fast.Next != nil && fast.Next.Next != nilit lands on the first middle (what you want before splitting a list in half). - Cycle detection: if there is a cycle, fast laps slow inside it and they meet; if not, fast hits nil.
- Cycle entrance (Floyd): let
a= distance from head to the cycle entrance,b= distance from the entrance to the meeting point,c= cycle length. Slow walkeda + b, fast walked2(a + b), and fast's extra distance is whole laps:a + b = k·c. Thereforea = k·c − b: a pointer starting at head and a pointer starting at the meeting point, both stepping by 1, meet exactly at the entrance afterasteps.
Gap pointers: k-th from the end
Advance fast k + 1 steps from a dummy, then move both until fast is nil; slow.Next is the k-th node from the end.
// removeNthFromEnd deletes the n-th node from the end (1 <= n <= length).
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{Next: head}
fast, slow := dummy, dummy
for range n + 1 { // open a gap of n nodes between slow and fast
fast = fast.Next
}
for fast != nil {
fast, slow = fast.Next, slow.Next
}
slow.Next = slow.Next.Next
return dummy.Next
}
Doubly linked lists, container/list, and LRU
A doubly linked list lets you unlink a node in O(1) when you already hold a pointer to it. Combine it with a map from key to node and you get an LRU cache: the map finds the node in O(1), the list keeps recency order, the most recently used node sits at the front, and eviction takes the tail.
Go's container/list is a ready-made doubly linked list (PushFront, MoveToFront, Remove, Back), but values are any, so you pay a type assertion and an extra allocation per element. A small generic implementation (Problem 4) is cleaner and is what interviewers want to see.
Why lists are rare in hot Go code — and where they appear
Every node is a separate heap allocation that the GC must trace, and traversal chases pointers across memory, so iteration is several times slower than over a slice of the same length (see Complexity Analysis). Where lists do appear in real systems: LRU/LFU caches, allocator free lists, the Linux kernel's intrusive lists, Redis lists (a quicklist: a linked list of compact listpack blocks — a hybrid that keeps locality), skip lists (Data Structures Inside Real Systems), and hash chains: an append-only audit log where each record stores the hash of the previous one is a linked list made tamper-evident, which is why banks use the idea for audit trails.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Slice | Contiguous, cache-friendly, cheap iteration and indexing | O(n) insert/delete in the middle | Default for sequences |
| Singly linked list | O(1) insert after a known node, cheap splitting/merging | O(n) access, pointer chasing, GC pressure | Interview problems, persistent/immutable lists |
| Doubly linked list | O(1) unlink/move given a node | Two pointers per node, more bookkeeping | LRU/LFU, ordered handles |
container/list | Standard, tested | any values, allocation per element | Quick prototypes, non-hot paths |
| Map + doubly linked list | O(1) get/put/evict | Memory overhead per entry, needs locking | In-process LRU caches |
| Ring buffer | Bounded, no allocation | Fixed capacity | FIFO without middle removal (Stacks, Queues & Monotonic Stacks) |
In practice
Problem 1 — Reverse Linked List (LeetCode 206)
Problem. Reverse a singly linked list and return the new head.
Approach. Iteratively with three pointers, or recursively: reverse the rest, then make the next node point back at the current one.
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for curr := head; curr != nil; {
next := curr.Next
curr.Next = prev
prev, curr = curr, next
}
return prev
}
func reverseListRec(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseListRec(head.Next)
head.Next.Next = head // the node after head now points back to head
head.Next = nil
return newHead
}
Complexity. O(n) time; O(1) space iterative, O(n) stack recursive. Follow-up: Reverse Nodes in k-Group (25) reuses the same loop per block.
Problem 2 — Linked List Cycle II (LeetCode 142)
Problem. Return the node where a cycle begins, or nil, using O(1) memory.
Approach. Floyd: detect the meeting point, then walk from head and from the meeting point in lockstep; they meet at the entrance (proof above). A map[*ListNode]bool also works in O(n) space — mention it as the brute force.
func detectCycle(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
if slow == fast { // inside the cycle; now find its entrance
for p := head; p != slow; {
p, slow = p.Next, slow.Next
}
return slow
}
}
return nil
}
Complexity. O(n) time, O(1) space. Find the Duplicate Number (287) is the same algorithm on the implicit list i → nums[i].
Problem 3 — Reorder List (LeetCode 143)
Problem. Rearrange L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place.
Approach. Three primitives composed: find the first middle with fast/slow, cut and reverse the second half, then weave the two halves. Interviewers like it because it tests whether your primitives are reliable.
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
slow, fast := head, head // 1. slow stops at the first middle
for fast.Next != nil && fast.Next.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
second := reverseList(slow.Next) // 2. cut and reverse the second half
slow.Next = nil
for first := head; second != nil; { // 3. weave
n1, n2 := first.Next, second.Next
first.Next = second
second.Next = n1
first, second = n1, n2
}
}
Complexity. O(n) time, O(1) space. Forgetting slow.Next = nil creates a cycle — the classic bug here.
Problem 4 — LRU Cache (LeetCode 146)
Problem. Design a cache with fixed capacity where Get and Put run in O(1), evicting the least recently used key when full.
Approach. Map from key to node; doubly linked list with head/tail sentinels so unlink and push-front never check for nil. Every access moves the node to the front; eviction removes tail.prev.
type entry[K comparable, V any] struct {
key K
val V
prev, next *entry[K, V]
}
// LRU is a fixed-capacity least-recently-used cache. Not safe for concurrent use.
type LRU[K comparable, V any] struct {
capacity int
items map[K]*entry[K, V]
head entry[K, V] // sentinel: head.next is the most recently used
tail entry[K, V] // sentinel: tail.prev is the least recently used
}
func NewLRU[K comparable, V any](capacity int) *LRU[K, V] {
c := &LRU[K, V]{capacity: capacity, items: make(map[K]*entry[K, V], capacity)}
c.head.next = &c.tail
c.tail.prev = &c.head
return c
}
func (c *LRU[K, V]) unlink(e *entry[K, V]) {
e.prev.next = e.next
e.next.prev = e.prev
}
func (c *LRU[K, V]) pushFront(e *entry[K, V]) {
e.prev = &c.head
e.next = c.head.next
c.head.next.prev = e
c.head.next = e
}
func (c *LRU[K, V]) Get(key K) (V, bool) {
e, ok := c.items[key]
if !ok {
var zero V
return zero, false
}
c.unlink(e)
c.pushFront(e)
return e.val, true
}
func (c *LRU[K, V]) Put(key K, val V) {
if c.capacity <= 0 {
return
}
if e, ok := c.items[key]; ok {
e.val = val
c.unlink(e)
c.pushFront(e)
return
}
if len(c.items) == c.capacity {
lru := c.tail.prev
c.unlink(lru)
delete(c.items, lru.key)
}
e := &entry[K, V]{key: key, val: val}
c.items[key] = e
c.pushFront(e)
}
Complexity. O(1) per operation, O(capacity) space. The node stores its key so eviction can delete the map entry. The sentinels live inside the struct, so the cache must never be copied by value — the constructor returns a pointer for that reason.
Production notes an architect should add unprompted:
- Concurrency: wrap with a
sync.Mutex(evenGetmutates the list, so anRWMutexread lock is not enough). Under high contention, shard: N independent LRUs selected by key hash. - Bounds by bytes, not count, and add TTLs for data that goes stale (FX rates, prices).
- Mature libraries:
hashicorp/golang-lru,groupcache/lru; for very high hit-rate needs, admission policies like TinyLFU (used by Ristretto) beat plain LRU. - Never use an evicting cache for correctness state. If idempotency keys live in an LRU, a busy period evicts them and a client retry double-charges. Use a durable store with a TTL longer than the retry window (Idempotency & Exactly-Once).
Practice list
- Easy: Reverse Linked List (206), Merge Two Sorted Lists (21), Linked List Cycle (141), Middle of the Linked List (876), Palindrome Linked List (234)
- Medium: Remove Nth Node From End of List (19), Reorder List (143), Linked List Cycle II (142), Add Two Numbers (2), Copy List with Random Pointer (138), LRU Cache (146), Find the Duplicate Number (287)
- Hard: Merge k Sorted Lists (23), Reverse Nodes in k-Group (25), LFU Cache (460)
Common pitfalls
- Losing the tail: rewiring
curr.Nextbefore saving it. Symptom: the list is suddenly one node long. - Nil dereference in fast/slow loops: checking
fast.Next.Nextwithout first checkingfast.Next. Symptom: panic on even-length or empty lists. - Not cutting after a split (
slow.Next = nil), producing a cycle and an infinite loop in tests. - Comparing values instead of node identity for cycles and intersections (LeetCode 160). Two different nodes can hold equal values.
- Special-casing the head instead of using a dummy, then missing the "delete the only node" case.
- Deep recursion on long lists: recursive reversal of 10⁶ nodes uses 10⁶ stack frames. Go grows the stack, but it costs memory and time; prefer iteration.
- LRU bugs: copying the cache struct (sentinel pointers now point into the old copy), reading under an
RWMutexread lock whileGetreorders the list (data race), or forgetting to update the value onPutof an existing key.
Interview angle
- Pointer problems are judged on clean, bug-free code: narrate invariants ("prev is the head of the reversed part"), draw the boxes, and test with lengths 0, 1, 2 and odd/even.
- For Floyd, be ready to prove the entrance step, not just recite it.
- LRU is one of the most common "design a data structure" questions at banks and e-commerce companies. A strong answer covers the O(1) structure, then moves to concurrency (mutex, sharding), memory bounds, TTL, and distributed caching (Caching, Redis Deep Dive — Redis approximates LRU by sampling keys rather than keeping a full list).
- Follow-ups: "Make it LFU" (frequency buckets, each a doubly linked list), "Make it thread-safe", "Distribute it across nodes" (Consistent Hashing).
- Red flags: reaching for
container/listwithout knowing its costs, an O(n) "move to front" by scanning, or using LRU semantics for data that must never be lost.
Self-check
1. Why does a dummy head simplify list code?
It guarantees every real node, including the first, has a predecessor. Insertions and deletions at the head become the same operation as anywhere else, and you return dummy.Next at the end. It removes a whole class of nil checks and the "delete the only node" bug.
2. Prove that resetting one pointer to head finds the cycle entrance in Floyd's algorithm.
At the meeting point, slow travelled a + b and fast 2(a + b); the difference a + b is a whole number of laps k·c. So a = k·c − b. Walking a steps from head reaches the entrance; walking a steps from the meeting point (which is b past the entrance) lands at b + k·c − b, i.e. the entrance after k laps. Both pointers arrive together.
3. Why does an LRU cache need a doubly (not singly) linked list?
On Get you must move an arbitrary node to the front in O(1). Unlinking requires updating the predecessor's next; with a singly linked list you would need to scan to find the predecessor (O(n)). The prev pointer makes unlink O(1).
4. Why might a slice-based queue outperform container/list even though both are O(1) per operation?
The slice is contiguous and allocates only on growth; container/list allocates one element per push and stores values as any (another allocation for non-pointer values). Lists also scatter nodes across the heap, causing cache misses and more GC tracing. Same Big-O, very different constants.
5. How do you find the middle node so that you can split a list into two halves of equal or near-equal length?
Use fast/slow pointers with the loop condition fast.Next != nil && fast.Next.Next != nil. Slow stops at the first middle; the second half starts at slow.Next, and you cut with slow.Next = nil. For odd lengths the first half gets the extra node.
6. Scenario: a payment service keeps processed idempotency keys in an in-memory LRU of 100k entries. What can go wrong?
During a traffic spike more than 100k payments arrive within the client retry window, so keys are evicted before retries stop; a retried request misses the cache and is processed again — a double charge. Also, each replica has its own cache, so a retry routed to another pod is never deduplicated. Idempotency state must be durable and shared (a database unique constraint or Redis with a TTL beyond the retry window); an LRU can only be an optimization in front of it.
Exercise
Turn the LRU into a production-shaped package:
ShardedLRU[K, V]with 16 shards selected bymaphashof the key, each shard anLRUguarded by async.Mutex.- Per-entry TTL (store an expiry time; treat expired entries as misses and remove them lazily).
- Capacity in bytes using a caller-supplied
size func(V) int. - Benchmarks with
b.RunParallelcomparing one global mutex against 16 shards at 8 and 64 goroutines.
Done when tests (including eviction order, TTL expiry and capacity 1) pass with -race, and the benchmark shows the contention difference with numbers you can explain.
Further reading
- Introduction to Algorithms (CLRS) — linked lists and hash tables chapters
- Donald Knuth, The Art of Computer Programming, Vol. 2 — Floyd's cycle-finding method (exercise in section 3.1)
- Go documentation:
container/list - Source code of
hashicorp/golang-lruandgolang/groupcache/lru— small, readable production LRUs - Redis documentation — "Key eviction" (approximated LRU and LFU)
Related
- Two Pointers & Sliding Window — the same pointer discipline on arrays.
- Heaps & Priority Queues — merging k sorted lists.
- Data Structures Inside Real Systems — skip lists, LFU and hash chains.
- Caching — eviction policies at system scale.
- Redis Deep Dive — how Redis approximates LRU/LFU.
- Generics — writing the generic LRU.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).