Two Speeds Through One List
Use slow and fast pointers for single-pass middle finding, Floyd cycle detection and entry recovery, k-th node from the end with a k-step lead, and two-list intersection.
Contentsand lesson path
On this page
- The problem
- Step 1: finding the middle in one pass without counting length
- Step 2: Floyd cycle detection—why fast must catch slow
- Step 3: k-th node from the end and two-list intersection
- Check your understanding
- Apply it
- Review prompt
Lessons of Linked Lists
- Nodes, References and Sentinels Concept · 20 min
- Lab: A Doubly Linked List with a Sentinel Lab · 30 min
- Reference Surgery: Reverse, Merge, Split Worked example · 25 min
- Two Speeds Through One List Worked example · 20 min
- Lists, Arrays or Deques? Concept · 15 min
- Check: Linked List Exercises Knowledge check · 8 questions
What you will learn
- Use fast and slow pointers to find the middle node and detect a cycle, and explain why the pointers must meet.
Prerequisites: Complexity Analysis
01. The problem
Suppose you receive only the head reference of a singly linked list and must answer structural questions in one traversal and O(1) extra space—no copying nodes into a Python list and no storing visited id(node) entries in a set: find the middle node, detect whether a buggy .next link forms a cycle (and locate where the cycle enters), locate the k-th node from the end, or check whether two lists merge into a shared suffix.
A two-pass count-then-walk approach fails immediately if a cycle exists (the first counting pass loops forever), while a seen: set[int] consumes O(n) extra memory. In this worked example we build and verify four two-pointer mechanics: 1x/2x middle finding, Floyd's cycle detection with its gap-shrinking proof, a fixed k-step lead, and length-equalizing head switching for intersection.
02. Step 1: finding the middle in one pass without counting length
Start both pointers at head: slow = fast = head. On each step k (while fast is not None and fast.next is not None:), slow advances 1 link (to 1-based position k + 1) while fast advances 2 links (to position 2k + 1). When fast lands on the last node or steps past it to None, slow sits halfway across the chain.
Compare an odd list 10 -> 20 -> 30 -> 40 -> 50 with an even list 10 -> 20 -> 30 -> 40 -> 50 -> 60. On the odd list, fast hops 10 -> 30 -> 50 (stopping because 50.next is None), leaving slow on the unique middle 30. On the even list, fast hops 10 -> 30 -> 50 -> None in three steps, leaving slow at 40 (the second middle node). By contrast, middle_first starts fast = head.next (at 20), hops 20 -> 40 -> 60, and stops because 60.next is None, leaving slow at 30 (the first middle node, which you used in split_middle).
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
val: int
next: "Node | None" = None
def from_list(vals: list[int]) -> Node | None:
dummy = tail = Node(0)
for v in vals:
tail.next = Node(v)
tail = tail.next
return dummy.next
def middle_second(head: Node | None) -> Node | None:
slow = 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
return slow
def middle_first(head: Node | None) -> Node | None:
if head is None:
return None
slow = head
fast: Node | None = head.next
while fast is not None and fast.next is not None:
assert slow.next is not None
slow = slow.next
fast = fast.next.next
return slow
odd = from_list([10, 20, 30, 40, 50])
even = from_list([10, 20, 30, 40, 50, 60])
m_odd = middle_second(odd)
m_even2 = middle_second(even)
m_even1 = middle_first(even)
print("odd middle:", m_odd.val if m_odd else None)
print("even second:", m_even2.val if m_even2 else None)
print("even first:", m_even1.val if m_even1 else None)odd middle: 30
even second: 40
even first: 3003. Step 2: Floyd cycle detection—why fast must catch slow
If a list contains a cycle of length L >= 1, fast never hits None. Once both pointers are inside the loop, why can fast never leap past slow forever—even when L is odd?
Measure the forward distance d along the cycle from fast ahead to slow (0 <= d < L). Each iteration advances slow by 1 (increasing d by 1) and advances fast by 2 (decreasing d by 2). The net change is 1 - 2 = -1 modulo L! Because d shrinks by exactly 1 node per step (d, d - 1, ..., 2, 1, 0), d cannot skip from 1 to -1 and must reach 0 within at most L iterations inside the cycle.
To locate the cycle entry node, suppose the tail before the entry has a edges and the meeting point sits b edges past the entry (0 <= b < L). When they first meet, slow has walked a + b steps and fast has walked 2(a + b) steps, which equals a + b + k * L for some positive integer k (fast lapped slow k times). Subtracting a + b gives a + b = k * L, so a = k * L - b. Therefore, resetting a fresh pointer p at head while keeping slow at the meeting point and advancing both at speed 1 moves p a steps to the entry node while slow walks a = k * L - b steps from b—completing k * L steps past the entry and landing on the exact same entry node!
Trace that on 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 30 (a = 2, L = 4): slow steps 10 -> 20 -> 30 -> 40 -> 50 while fast jumps 10 -> 30 -> 50 -> 30 -> 50, meeting at 50 (b = 2). Phase 2 walks p (10 -> 20 -> 30) and slow (50 -> 60 -> 30) two steps each to converge at entry 30.
When NOT to use Floyd's algorithm: in debugging scripts over small in-memory graphs where O(n) space is fine, a seen: set[int] storing id(node) stops on the very first revisit to the entry node with simpler code and zero phase-2 math.
10 ---> 20 ---> [30] ---> [40] ---> [50] ---> [60]
^ |
|_____________________________| (cycle L = 4)
Inside cycle: slow += 1, fast += 2 => forward gap (fast -> slow) drops by 1from dataclasses import dataclass
@dataclass(eq=False)
class Node:
val: int
next: "Node | None" = None
def has_cycle(head: Node | None) -> bool:
slow = 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:
return True
return False
def cycle_start(head: Node | None) -> Node | None:
slow = 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:
p = head
while p is not slow:
assert p is not None and slow is not None
p = p.next
slow = slow.next
return p
return None
nodes = [Node(v) for v in (10, 20, 30, 40, 50, 60)]
for i in range(5):
nodes[i].next = nodes[i + 1]
print("acyclic has_cycle:", has_cycle(nodes[0]))
nodes[5].next = nodes[2]
entry = cycle_start(nodes[0])
print("cyclic has_cycle:", has_cycle(nodes[0]))
print("cycle entry:", entry.val if entry else None)
solo = Node(7)
solo.next = solo
solo_entry = cycle_start(solo)
print("self-loop:", has_cycle(solo), "| entry:", solo_entry.val if solo_entry else None)acyclic has_cycle: False
cyclic has_cycle: True
cycle entry: 30
self-loop: True | entry: 704. Step 3: k-th node from the end and two-list intersection
Two related single-pass, O(1)-space pointer tricks complete your linked-list toolkit:
k-th node from the end with ak-step lead: moveleadforwardktimes whilefollowstays athead(ifleadhitsNonebeforeksteps, the list has fewer thanknodes so returnNone). Now advance bothleadandfollowat 1x together untillead is None: sinceleadalways staysksteps ahead,followlands exactlyknodes beforeNone(sok = 1returns the tail node).- Intersection point of two acyclic lists (
head_a,head_b): suppose list A haslen_anodes beforeNoneand list B haslen_bnodes beforeNone, sharing a common suffix ofcnodes (0if disjoint). Startpa = head_aandpb = head_b, and advancepa = pa.next if pa is not None else head_b(and symmetricallypb = pb.next if pb is not None else head_a). Each pointer walks its own list, steps ontoNone, and switches to the other list's head—traversinglen_a + 1 + len_btransitions in total! If the lists intersect,pa is pbmatches at the exact shared entry node; if they are disjoint, bothpaandpbreachNonesimultaneously—afterlen_asteps if the lengths are equal, or otherwise afterlen_a + len_b + 1steps—ending the loop cleanly withNone.
Predict before running: in the snippet below, ha has length 4 (10 -> 20 -> 40 -> 50) and hb has length 3 (99 -> 40 -> 50), sharing node 40. Why must the comparison use pa is not pb rather than pa.val != pb.val?
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
val: int
next: "Node | None" = None
def from_list(vals: list[int]) -> Node | None:
dummy = tail = Node(0)
for v in vals:
tail.next = Node(v)
tail = tail.next
return dummy.next
def kth_from_end(head: Node | None, k: int) -> Node | None:
if k <= 0:
return None
lead = follow = head
for _ in range(k):
if lead is None:
return None
lead = lead.next
while lead is not None:
assert follow is not None
lead = lead.next
follow = follow.next
return follow
def intersection_node(head_a: Node | None, head_b: Node | None) -> Node | None:
pa, pb = head_a, head_b
while pa is not pb:
pa = pa.next if pa is not None else head_b
pb = pb.next if pb is not None else head_a
return pa
seq = from_list([10, 20, 30, 40, 50])
k2 = kth_from_end(seq, 2)
print("2nd from end:", k2.val if k2 else None, "| k=8:", kth_from_end(seq, 8))
shared = Node(40, Node(50))
ha = Node(10, Node(20, shared))
hb = Node(99, shared)
hit = intersection_node(ha, hb)
print("shared node val:", hit.val if hit else None)
print("disjoint:", intersection_node(from_list([1, 2, 3]), from_list([4, 5])))2nd from end: 40 | k=8: None
shared node val: 40
disjoint: None05. Check your understanding
06. Apply it
Write a pytest suite verifying middle_second, has_cycle, cycle_start, kth_from_end, and intersection_node on: empty list None, 1-node acyclic list, 1-node self-loop, odd/even acyclic lists, k = 1 and k > len, intersecting lists with equal vs unequal prefix lengths, and disjoint lists.
Next, measure when linked lists lose to built-in Python structures and when dict + DLL genuinely wins in Lists, Arrays or Deques?.
07. Review prompt
Without looking back:
- Why does
slow = fast = headstop at the second middle on even lengths whilefast = head.nextstops at the first middle? - Prove in two sentences why
2xvs1xcannot skip overslowinside a cycle of any lengthL >= 1. - Why does the head-switching intersection loop terminate even when two lists share no nodes at all?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.