Cycle Detection in Linked Lists

easyPython

Lesson

Floyd's Cycle Detection Algorithm

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.

The Core Concept

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:

  • Slow pointer (tortoise): moves one step at a time
  • Fast pointer (hare): moves two steps at a time

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.

Why This Works

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:

  • Time Complexity: O(n) - we visit each node at most twice
  • Space Complexity: O(1) - we only use two pointer variables

Key Advantages

  • No extra memory needed (unlike marking visited nodes)
  • Works on any sequence, not just linked lists
  • Guaranteed to terminate in linear time
Example
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
L6Slow pointer moves one step at a time
L7Fast pointer moves two steps at a time
L8When they meet, we've detected a cycle

Key Takeaways

  • •Two pointers moving at different speeds can detect cycles in O(1) space
  • •The fast pointer will either meet the slow pointer (cycle) or reach the end (no cycle)
  • •This technique works for any sequence structure, not just linked lists
Loading...