Two Pointers: Fast & Slow Resource - aloalgo

Two Pointers: Fast & Slow

The fast and slow pointer technique (also called Floyd's algorithm) uses two pointers moving at different speeds. The slow pointer moves one step at a time, while the fast pointer moves two steps. This pattern is essential for linked list problems.

The Pattern

This simple pattern solves two common problems:
  • Finding the middle: When fast reaches the end, slow is at the middle
  • Detecting cycles: If there's a cycle, fast and slow will eventually meet

Find Middle of Linked List

When the fast pointer reaches the end of the list, the slow pointer will be at the middle. This works because fast moves twice as fast as slow.
Time: O(n) - single pass through the listSpace: O(1) - only two pointers

Detect Cycle in Linked List

Idea: If there's a cycle, the fast pointer will eventually catch up to the slow pointer. If fast reaches the end (null), there's no cycle.
  • Time: O(n)
  • Space: O(1)

Find Where Cycle Begins

Once we detect a cycle, we can find where it starts. After slow and fast meet, reset one pointer to head and move both at the same speed. They'll meet at the cycle's start.
The math: Let's say the distance from head to cycle start is a, and the meeting point is b nodes into the cycle. When they meet, slow has traveled a + b, and fast has traveled 2(a + b). The extra distance fast traveled is exactly the cycle length. This means moving a more steps from the meeting point brings us back to the cycle start.

Palindrome Linked List

Use fast/slow to find middle, reverse second half, compare.

Find the Duplicate Number

Floyd's algorithm can also solve the "find duplicate in array" problem by treating the array as a linked list where nums[i] points to the next node.

Happy Number

A number is "happy" if repeatedly summing the squares of its digits eventually reaches 1. If it enters a cycle, it's not happy. Use Floyd's algorithm to detect the cycle.

Common Interview Tips

  1. Check fast.next: Always check both fast and fast.next before advancing to avoid null pointer errors.
  2. Know both applications: The same pattern solves cycle detection and finding the middle.
  3. Space efficiency: This technique uses O(1) space compared to O(n) for using a hash set.
  4. Think abstractly: Any sequence where each element points to another (like array indices) can be treated as a linked list for cycle detection.

Practice Problems

Was this helpful?
© 2026 aloalgo. All rights reserved.