Lesson 124 of 296
Fast and slow pointers
What you will learn
- The fast and slow pointer idea (Floyd's algorithm)
- A first look at linked list nodes
- Linked List Cycle
- Middle of a linked list
- Happy Number
- Find the Duplicate Number
On this page
The idea
Move two pointers through a sequence at different speeds: slow moves one step, fast moves two steps.
- If the sequence has a cycle (it loops back on itself), the fast pointer eventually catches up with the slow one, like a faster runner lapping a slower one on a track.
- If there is no cycle, the fast pointer reaches the end.
- When fast reaches the end, slow is in the middle.
This is called Floyd's cycle detection or the "tortoise and hare" algorithm. It uses O(1) space, unlike remembering every visited item in a Set.
Linked list nodes (first look)
A linked list is a chain of nodes. Each node stores a value and a reference to the next node. The last node's next is null. Lesson 133 covers linked lists in full.
class ListNode {
val: number;
next: ListNode | null;
constructor(val: number, next: ListNode | null = null) {
this.val = val;
this.next = next;
}
}
function listFromArray(values: number[]): ListNode | null {
let head: ListNode | null = null;
for (let i = values.length - 1; i >= 0; i--) {
head = new ListNode(values[i]!, head);
}
return head;
}
function listToArray(head: ListNode | null): number[] {
const result: number[] = [];
for (let node = head; node !== null; node = node.next) result.push(node.val);
return result;
}Linked List Cycle
Problem (LeetCode 141): does the list contain a cycle (some node's next points back to an earlier node)?
function hasCycle(head: ListNode | null): boolean {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}O(n) time, O(1) space. (A Set of visited nodes also works: O(n) space.)
Follow-up (LeetCode 142): where does the cycle start? After they meet, move one pointer back to the head and step both one at a time; they meet at the start of the cycle. (This follows from the distances involved; knowing the trick is usually enough.)
function detectCycleStart(head: ListNode | null): ListNode | null {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) {
let finder = head;
while (finder !== slow) {
finder = finder!.next;
slow = slow!.next;
}
return finder;
}
}
return null;
}Middle of the Linked List
Problem (LeetCode 876): return the middle node (the second middle if there are two).
function middleNode(head: ListNode | null): ListNode | null {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
}When fast has gone the whole way, slow has gone half way. One pass, O(1) space. This is a building block for Reorder List (Lesson 133) and for merge sort on linked lists.
Happy Number
Problem (LeetCode 202): replace a number by the sum of the squares of its digits, repeatedly. It is "happy" if it reaches 1. Otherwise it loops forever.19 → 1² + 9² = 82 → 68 → 100 → 1: happy.
The sequence of numbers either reaches 1 or enters a cycle, so this is cycle detection on numbers instead of nodes:
function digitSquareSum(n: number): number {
let sum = 0;
while (n > 0) {
const digit = n % 10;
sum += digit * digit;
n = Math.floor(n / 10);
}
return sum;
}
function isHappy(n: number): boolean {
let slow = n;
let fast = digitSquareSum(n);
while (fast !== 1 && slow !== fast) {
slow = digitSquareSum(slow);
fast = digitSquareSum(digitSquareSum(fast));
}
return fast === 1;
}Find the Duplicate Number
Problem (LeetCode 287): an array of n + 1 numbers, each from 1 to n, has exactly one repeated number (possibly repeated more than once). Find it without changing the array and with O(1) extra space.
Trick: treat each value as a pointer to an index: from index i go to nums[i]. Because two positions hold the same value, two "arrows" point to the same index, which creates a cycle, and the cycle starts at the duplicate value. Then use the cycle-start technique.
function findDuplicate(nums: number[]): number {
let slow = nums[0]!;
let fast = nums[0]!;
do {
slow = nums[slow]!;
fast = nums[nums[fast]!]!;
} while (slow !== fast);
let finder = nums[0]!;
while (finder !== slow) {
finder = nums[finder]!;
slow = nums[slow]!;
}
return finder;
}O(n) time, O(1) space. This one is hard to invent under pressure; knowing it shows depth. Simpler answers: a Set (O(n) space) or sorting (changes the array).
How to say it in an interview
"Fast and slow pointers move at one and two steps. If there is a cycle, fast eventually meets slow; if not, fast reaches the end, at which point slow is at the middle. It detects cycles in O(1) space instead of a visited set. To find where a cycle starts, I reset one pointer to the head and move both one step until they meet. The same idea applies to number sequences, like Happy Number, and to Find the Duplicate Number by treating values as next pointers."
Key words
| Word | Meaning |
|---|---|
| Fast and slow pointers | Two pointers moving at different speeds |
| Floyd's algorithm | Tortoise-and-hare cycle detection |
| Cycle | A path that loops back on itself |
| Node | One item in a linked list, with a value and a next reference |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.