Data Structures19 sections · 729 units
Open in Course

Finding Cycle Start

Where does the cycle begin?

Once you detect a cycle, finding where it starts requires a clever insight.

After fast and slow meet inside the cycle, reset one pointer to the head. Move both pointers one step at a time. They'll meet at the cycle start.

# After detecting cycle (slow == fast)
slow = head
while slow != fast:
    slow = slow.next
    fast = fast.next
return slow # cycle start

Why does this work? Let aa = distance from head to cycle start, bb = distance from cycle start to meeting point, cc = cycle length.

When they first meet: slow traveled a+ba + b, fast traveled a+b+kca + b + kc for some kk. Since fast moves twice as fast: 2(a+b)=a+b+kc2(a + b) = a + b + kc, so a=kcba = kc - b. So walking aa steps from the meeting point lands exactly at the cycle start.