Why Linked Lists Trip Strong Engineers
Linked-list questions are less about algorithmic cleverness and more about pointer discipline under pressure. As summarized in the NeetCode roadmap breakdown, linked lists train you to manipulate references in place without allocating an array copy.
Almost every bug candidates hit comes from losing a reference before reading .next, treating the first node differently from interior nodes, or indexing past None. Three small habits remove almost all of that friction.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Intuition Behind the Three Core Tricks
1. Sentinel dummy nodes erase head special cases
Whenever an operation might remove, replace, or reorder the original head, create dummy = ListNode(0, head) and track a lagging cursor prev = dummy. Because head now sits behind a real node, deleting node 0 uses the exact same prev.next = prev.next.next logic as deleting node 5, and you simply return dummy.next.
This same sentinel pattern cleans up merging two sorted lists and removing the $n$-th node from the end: keep a tail pointer starting at dummy, append whichever node holds the smaller value, and attach the remaining non-empty chain afterward. For -th from the end, advance a lead pointer n steps ahead from dummy, then move lead and lag together until lead.next is None; lag lands squarely on the predecessor of the node to delete, even when deleting the first element.
2. Fast-and-slow pointers and Floyd's cycle geometry
Moving slow by one step and fast by two steps solves two classic problems in one pass without storing nodes in a set:
- Middle split: When
fastreaches the end (not fast or not fast.next),slowrests at the midpoint. Initializingfast = headstopsslowon the second middle for even lengths ([1, 2, 3, 4]gives3), whereasfast = head.nextstopsslowon the first middle (2), which is critical when cutting a list into two non-overlapping halves (mid.next = None) for merge sort or palindrome verification. - Cycle entry: As formalized in the Wikipedia cycle detection analysis, let be the steps from
headto cycle entry , be steps from to meeting node , and be cycle length. At collision,fasttraveled steps whileslowtraveled , so is a multiple of . Thus walking more steps from reaches again. Resetting one pointer toheadand stepping both by 1 brings them together at .
When linked-list questions escalate into system-design classics like LRU Cache, pair a sentinel-bounded doubly linked list (head_sentinel and tail_sentinel) with a hash map from key to node reference so moving an accessed item to the front and evicting the oldest tail both run in without scanning.
3. Saving nxt before reversing links
Full reversal swaps three variables per node: save nxt = curr.next, flip curr.next = prev, advance prev = curr, and step curr = nxt. Sublist reversal (reverse_between) gets even cleaner with head-insertion: anchor pre right before the segment and tail on its first node, then pull each nxt = tail.next straight behind pre.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Working Python Code
Here is a self-contained module implementing ListNode, in-place reversal (reverse_list), sublist reversal (reverse_between), and Floyd's cycle entry detector (detect_cycle), verified with test lists.
from __future__ import annotations
class ListNode:
def __init__(self, val: int = 0, next_node: ListNode | None = None) -> None:
self.val = val
self.next = next_node
def build_list(values: list[int]) -> ListNode | None:
dummy = ListNode()
tail = dummy
for v in values:
tail.next = ListNode(v)
tail = tail.next
return dummy.next
def to_list(head: ListNode | None) -> list[int]:
out: list[int] = []
curr = head
while curr is not None:
out.append(curr.val)
curr = curr.next
return out
def reverse_list(head: ListNode | None) -> ListNode | None:
prev: ListNode | None = None
curr = head
while curr is not None:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
def reverse_between(head: ListNode | None, left: int, right: int) -> ListNode | None:
if head is None or left == right:
return head
dummy = ListNode(0, head)
pre = dummy
for _ in range(left - 1):
assert pre.next is not None
pre = pre.next
tail = pre.next
assert tail is not None
for _ in range(right - left):
nxt = tail.next
assert nxt is not None
tail.next = nxt.next
nxt.next = pre.next
pre.next = nxt
return dummy.next
def detect_cycle(head: ListNode | None) -> ListNode | None:
slow = head
fast = head
while fast is not None and fast.next is not None:
assert slow is not None
slow = slow.next
fast = fast.next.next
if slow is fast:
entry = head
while entry is not slow:
assert entry is not None and slow is not None
entry = entry.next
slow = slow.next
return entry
return None
if __name__ == "__main__":
assert to_list(reverse_list(build_list([1, 2, 3, 4]))) == [4, 3, 2, 1]
assert to_list(reverse_between(build_list([1, 2, 3, 4, 5]), 2, 4)) == [1, 4, 3, 2, 5]
nodes = [ListNode(i) for i in range(4)]
for idx in range(3):
nodes[idx].next = nodes[idx + 1]
nodes[3].next = nodes[1]
assert detect_cycle(nodes[0]) is nodes[1]
print("reverse_between:", to_list(reverse_between(build_list([1, 2, 3, 4, 5]), 2, 4)))
entry = detect_cycle(nodes[0])
print("cycle entry val:", entry.val if entry else None)Running this script produces:
reverse_between: [1, 4, 3, 2, 5]
cycle entry val: 1Complexity Analysis
| Trick / Algorithm | Time Complexity | Extra Space | Notes |
|---|---|---|---|
| Dummy-head deletion / merge | Sentinel removes separate head branch | ||
| Three-pointer in-place reversal | Fixed number of pointer updates per node | ||
| Floyd's cycle detection | At most steps after entering cycle |
Comparing Blind 75 against NeetCode 150, linked-list questions stay compact in both tracks precisely because interviews test pointer hygiene over heavy theory. Recursive reversal is clean to write, yet it consumes call-stack frames and risks hitting Python's default recursion limit on long chains, so I always code the iterative pointer loop in interviews.
Common Mistakes and When I Skip In-Place Rewiring
Watch out for these recurring errors:
- Returning `head` instead of `dummy.next`: After modifying node 0 (such as reversing from position
1or removing the first element),headstill points to the old first node, which might now sit mid-list or unlinked. - Checking only `while fast:`: Calling
fast.next.nextwhenfast.nextisNonecrashes on odd-length acyclic lists. - Comparing node values instead of identity (`is`): In cycle detection, duplicate
.valintegers exist in distinct nodes; always testslow is fast, neverslow.val == fast.val. - Creating self-loops during reversal: Writing
nxt.next = pre.nextbeforetail.next = nxt.nextwhen reversing sublists corrupts the chain iftailandnxtare adjacent.
I skip -space in-place mutation whenever a question forbids mutating input nodes (for example, concurrent readers or persistent immutable structures), or when an interviewer specifically permits copying values into a hash table for rapid prototyping before tightening space.
Practice Problems
Apply these pointer tricks across two foundational prompts:
- Reverse Linked List: Write the iterative three-pointer loop cleanly and trace the final state when the input has zero or one node.
- Linked List Cycle II: Implement Floyd's two-phase cycle entry algorithm without using a
setand verify botha == 0(cycle starts athead) and acyclic lists.
