Core Module
12 min forge
Fast & Slow Pointers
Master the 'Hare and Tortoise' technique to solve cycle detection and midpoint problems efficiently.
ππ’ Fast & Slow Pointers: The Hare and Tortoise
The Fast and Slow pointer technique (also known as Floyd's Cycle-Finding Algorithm) uses two pointers that move through a sequence at different speeds. By observing their interaction, we can find properties of the sequence that would otherwise require extra space.
π‘ The Logic (ELI5)
Imagine two people running on a track:
- Runner A (Slow): Takes 1 step at a time.
- Runner B (Fast): Takes 2 steps at a time.
- On a straight road: The Fast runner will just finish twice as fast and never see the Slow runner again.
- On a circular track: The Fast runner will eventually lap the Slow runner and they will meet again.
- Finding the middle: When the Fast runner finishes the track, the Slow runner (who was half as fast) will be standing exactly in the middle.
π The Deep Dive
Pattern 1: Find the Middle
- Move
slowby 1 step,fastby 2 steps. - When
fastreaches the end (null),slowis at the middle. - Complexity: $O(n)$ time, $O(1)$ space.
Pattern 2: Cycle Detection
- Move
slowby 1 step,fastby 2 steps. - If
slow === fastat any point, there is a Cycle. - If
fastreaches null, there is No Cycle. - Complexity: $O(n)$ time, $O(1)$ space.
π οΈ Code Forge: Finding the Midpoint
javascript Standard/** * Find the middle node of a Linked List. * If the list has even nodes, returns the second middle. */ function findMiddle(head) { let slow = head; let fast = head; // While fast can still take two steps while (fast !== null && fast.next !== null) { slow = slow.next; // 1 step fast = fast.next.next; // 2 steps } return slow; // slow is now at the middle } /** * Detect a Cycle in a Linked List */ function hasCycle(head) { let slow = head; let fast = head; while (fast !== null && fast.next !== null) { slow = slow.next; fast = fast.next.next; // They met! A loop exists. if (slow === fast) return true; } return false; }
π― Interview Pulse
Why is this better?
Without this technique, you'd need a Set to store visited nodes to detect a cycle ($O(n)$ space). This technique uses $O(1)$ space.
Must-Practice Problems
- Linked List Cycle II: Find the starting node of the cycle.
- Palindrome Linked List: Find the middle, reverse the second half, and compare.
- Remove N-th Node from End: Use two pointers with a fixed distance between them.
- Happy Number: Yes, the "Happy Number" math problem is actually a cycle detection problem!