Fast & Slow Pointers
Signal: a linked list or a sequence where each value points to a "next" position (an index, a function f(x)); questions about cycles, the middle, or a duplicate with O(1) extra space.
Core idea: move one pointer 1 step and another 2 steps. On a cycle, the fast pointer gains one step per move and must meet the slow one; without a cycle, the fast pointer hits the end. When fast reaches the end of a list, slow is at the middle.
Floyd's algorithm in two phases
- Detect: advance
slowby 1 andfastby 2 until they meet (cycle) orfasthits null (no cycle). - Find the entrance: reset one pointer to the start, then advance both by 1; they meet at the cycle's first node.
Why phase 2 works: let the distance from the head to the entrance be a, and the meeting point be b steps into a cycle of length c. Slow traveled a + b; fast traveled 2(a + b) = a + b + k·c, so a = k·c − b. Walking a steps from the head and a steps from the meeting point both land on the entrance.
def cycle_start(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
p = head
while p is not slow:
p, slow = p.next, slow.next
return p
return NoneThe same trick works on implicit linked lists: "next" can be nums[i] (Find the Duplicate Number) or f(n) = the sum of squared digits (Happy Number).