sagelearnai

Linked List Cycle II

Difficulty: Medium · Pattern: Fast & Slow Pointers · LeetCode #142

Return the node where the cycle begins, or null if there is no cycle. Don't modify the list. Use O(1) memory.

The tests build the list from [values, pos], where the tail links to index pos (−1 means no cycle). They report the index of the node you return (−1 for null).

Examples

text
[3,2,0,-4], pos = 1  →  index 1    (tail −4 links back to node 2)
[1,2], pos = 0       →  index 0
[1], pos = -1        →  -1

Hints

  1. First detect the cycle with Floyd's algorithm (slow moves 1, fast moves 2).
  2. After they meet, move one pointer back to head. Advance both one step at a time. Where do they meet?

Approach

Floyd's algorithm, phase 2. Let a be the distance from the head to the entry, b the distance from the entry to the meeting point, and c the cycle length. At the meeting, slow has moved a + b and fast has moved 2(a + b), and fast has lapped slow some whole number of cycles: a + b = k·c. So a = k·c − b. Walking a steps from the meeting point lands exactly on the entry, and walking a steps from the head also lands on the entry. So a pointer from the head and a pointer from the meeting point, both moving at speed 1, meet at the entry.

The same argument powers Find the Duplicate Number.

Complexity

Time: O(n). Space: O(1).

Python solution
def detectCycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            p = head
            while p is not slow:
                p = p.next
                slow = slow.next
            return p
    return None
JavaScript solution
function detectCycle(head) {
  let slow = head, fast = head;
  while (fast && fast.next) {
    slow = slow.next; fast = fast.next.next;
    if (slow === fast) {
      let p = head;
      while (p !== slow) { p = p.next; slow = slow.next; }
      return p;
    }
  }
  return null;
}