Floyd's cycle detection algorithm, also known as the "tortoise and hare" algorithm, is a clever technique for detecting cycles in sequences using two pointers that move at different speeds.
Imagine two runners on a circular track: one runs at normal speed (tortoise) and another runs twice as fast (hare). If the track is circular, the faster runner will eventually lap the slower one and they'll meet. If the track has an end, the faster runner will reach the finish line first.
This same principle applies to linked lists. We use two pointers:
If there's a cycle in the linked list, the fast pointer will eventually "catch up" to the slow pointer inside the cycle. If there's no cycle, the fast pointer will reach the end of the list (null) first.
The mathematical reason this works is based on relative speed. Inside a cycle, the fast pointer gains one position on the slow pointer with each iteration. Since the cycle has finite length, the fast pointer will eventually close the gap and meet the slow pointer.
The algorithm is efficient because:
1def find_duplicate_in_array(nums):
2 """Example: Find duplicate in array using Floyd's algorithm"""
3 # Treat array as linked list: nums[i] points to nums[nums[i]]
4 slow = nums[0]
5 fast = nums[0]
6
7 # Phase 1: Detect if cycle exists
8 while True:
9 slow = nums[slow] # Move one step
10 fast = nums[nums[fast]] # Move two steps
11 if slow == fast:
12 break
13
14 # Phase 2: Find start of cycle (the duplicate)
15 slow = nums[0]
16 while slow != fast:
17 slow = nums[slow]
18 fast = nums[fast]
19
20 return slow