sagelearnai

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

  1. Detect: advance slow by 1 and fast by 2 until they meet (cycle) or fast hits null (no cycle).
  2. 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.

python
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 None

The 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).

Problems

  1. Middle of the Linked List (Easy): Fast moves 2, slow moves 1
  2. Happy Number (Easy): Floyd cycle detection on the digit-square-sum sequence
  3. Palindrome Linked List (Easy): Find middle (fast/slow), reverse second half, compare, (restore)
  4. Linked List Cycle II (Medium): After slow/fast meet, restart one pointer at head; they meet at the cycle entry
  5. Find the Duplicate Number (Medium): Treat i → nums[i] as a linked list; the duplicate is the cycle entry (Floyd)
  6. Circular Array Loop (Medium): Fast/slow from each start, same-direction only, reject self-loops, mark dead paths