Fast and slow pointers
medium 20 minTwo pointers walk the same chain, one node at a time and two nodes at a time.
Video lesson · Chapter 1 of 8
The looping film leader
The tortoise and the hare in 75 seconds
1:15Reel coming soon
How it works
Step through the idea, or press Play.
Run two speeds. Slow moves one node per step, fast moves two, both from the head
Understand it
Start here
Two speeds, one chain
You met the basic moves in Singly linked list (find the middle, detect a cycle) and the general idea of two indexes in Two pointers. This page goes further: why the hare must catch the tortoise, how to find where a loop starts and how long it is, and four classic problems that are secretly the same trick.
Slow, the tortoise
slow = slow.next. One node per step.Fast, the hare
fast = fast.next.next. Two nodes per step, so it has always covered twice the distance.Only two pointers
No visited set, no copy of the list: extra space, time.
The shape
Lists that end and lists that loop
A singly linked list either ends in None or, because some node's next points back to an earlier node, ends in a loop. Drawn out, a looping list looks like the Greek letter rho (ρ): a straight tail of nodes leading into a loop of nodes.
The rho shape used on this page
| What happens | What it means | Where slow is |
|---|---|---|
fast or fast.next becomes None | The list ends: no cycle | The middle node |
slow is fast after a step | The list loops | Somewhere inside the loop, nodes past the entrance |
The proof
Why the hare always catches the tortoise
Once slow enters the loop (after steps), fast is already somewhere in it. Let be how many nodes fast must still cover to land on slow, with . Each step fast moves 2 and slow moves 1, so fast gains exactly one node.
The gap shrinks by one per step
So the whole run is linear
Pattern 1
Detecting a cycle with Floyd's algorithm
Floyd's cycle detection
class Node: def __init__(self, val, next=None): self.val = val self.next = nextdef has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return Falsenodes = [Node(v) for v in range(1, 7)]for x, y in zip(nodes, nodes[1:]): x.next = yprint(has_cycle(nodes[0])) # False: 1 -> ... -> 6 -> Nonenodes[5].next = nodes[2] # 6 -> 3 makes the rhoprint(has_cycle(nodes[0])) # TrueFloyd's two pointers
- extra space
- Works on any
nextfunction, not just lists - Also yields the meeting point for phase 2
A visited set
- extra space
- Needs hashable nodes or values
- Simpler to write, fine when memory is not a concern
Pattern 2
Finding where the cycle starts
Name the distances: from the head to the entrance, from the entrance to the meeting point, the loop length. When they meet, fast has walked twice as far as slow and has gone round the loop some whole number of times more.
The distance proof
Phase 2: from meeting point to entrance
| Step | slow | fast | Note |
|---|---|---|---|
| phase 1 end | 5 | 5 | met after 4 steps; slow walked 4, fast 8 |
| reset | 1 | 5 | slow back to the head |
| 1 | 2 | 6 | both move one |
| 2 | 3 | 3 | meet at the entrance, after steps |
Pattern 3
Measuring the cycle length
Once you hold any node inside the loop (the meeting point or the entrance), keep one pointer still and walk the other until it comes back, counting hops. That count is . In the example, from node 3: 4, 5, 6, 3 gives .
def cycle_length(node): # node is any node inside the loop length, walk = 1, node.next while walk is not node: length, walk = length + 1, walk.next return lengthPattern 4
The middle of a list: first or second
With no loop, fast reaches the end when slow has done half the walk. On an even length there are two middles, and the loop condition picks which one you get.
Where slow stops
| List | while fast and fast.next | while fast.next and fast.next.next | Typical use |
|---|---|---|---|
| 1 2 3 4 5 | 3 | 3 | either |
| 1 2 3 4 5 6 | 4 (second middle) | 3 (first middle) | first: split for merge sort; second: LeetCode middle node |
fast.next straight away.Pattern 5
Happy numbers: a list you never build
Replace by the sum of the squares of its digits and repeat. is happy if this reaches 1, for example . Each number has exactly one next number, so the sequence is an implicit linked list with next = next_num(n), and Floyd works on it without storing a single value.
Why the sequence must repeat
n = 2 is not happy
def next_num(n): return sum(int(d) ** 2 for d in str(n))def is_happy(n): slow = fast = n while True: slow = next_num(slow) fast = next_num(next_num(fast)) if fast == 1: return True if slow == fast: return Falseprint([n for n in range(1, 50) if is_happy(n)])# [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]Pattern 6
Find the duplicate: an array as a linked list
An array of numbers, each between 1 and , must repeat some value. Find it without changing the array and in extra space. Read index as a node whose next is nums[i]. No value is 0, so index 0 is the head. The repeated value has two arrows pointing into it, which makes it the entrance of a loop: phase 1 plus phase 2 returns it.
nums = [1, 3, 4, 2, 2] as a list
| Approach | Time | Extra space | Changes the array? |
|---|---|---|---|
| Sort, then scan neighbours | or | yes | |
| Hash set of seen values | no | ||
| Binary search on the value range (count values ≤ mid) | no | ||
| Floyd on the index graph | no |
def find_duplicate(nums): slow = fast = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow = 0 while slow != fast: slow, fast = nums[slow], nums[fast] return slowprint(find_duplicate([1, 3, 4, 2, 2])) # 2print(find_duplicate([3, 1, 3, 4, 2])) # 3print(find_duplicate([2, 2, 2, 2, 2])) # 2Pattern 7
Palindrome linked list: middle, reverse, compare
- 1Find the middleslow and fast; slow stops on the middle
- 2Reverse the second halfflip next pointers from slow to the end
- 3Comparewalk head and the reversed half together
- 4Restore (optional)reverse the second half back
Each pass covers about half the list, so the total is $O(n)$ time and $O(1)$ space.
class Node: def __init__(self, val, next=None): self.val = val self.next = nextdef is_palindrome(head): slow = fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next prev = None while slow: # reverse from the middle nxt = slow.next slow.next = prev prev, slow = slow, nxt left, right = head, prev while right: # right half is never longer if left.val != right.val: return False left, right = left.next, right.next return Truedef build(vals): head = None for v in reversed(vals): head = Node(v, head) return headprint(is_palindrome(build([1, 2, 3, 2, 1]))) # Trueprint(is_palindrome(build([1, 2, 2, 1]))) # Trueprint(is_palindrome(build([1, 2, 3]))) # FalseChoosing
When to reach for fast and slow pointers
Which variant do I need?
| Problem | Signal | Key insight | Time / space |
|---|---|---|---|
| Linked list cycle | slow is fast | They meet inside the loop | / |
| Cycle start | reset slow to head | , both arrive together | / |
| Cycle length | walk until back | count one lap | / |
| Middle node | fast.next is None | slow covered half | / |
| Happy number | sum of squared digits | same as cycle detection | / |
| Find the duplicate | values 1 to in slots | duplicate is the loop entrance | / |
| Palindrome list | compare ends of a singly list | middle + reverse half | / |
Use it when
- Detecting cycles in lists or in any repeated function
- Finding the middle in one pass and space
- Finding the start or length of a cycle
- Happy number, duplicate number, palindrome list
Not ideal for
- Problems that need random access by index
- When you must record every node visited anyway
- Data that is not a chain with one next per element
- Sorted arrays, where opposite-end two pointers fit better
Recap
Key takeaways
Key points
- Slow moves 1, fast moves 2, both from the head; move first, then compare with
is. - Fast hits
None: no loop, and slow is on the middle (second middle withwhile fast and fast.next). - In a loop the gap closes by exactly one node per step, so they meet within steps of slow entering: time, space.
- Cycle start: , so reset one pointer to the head and move both by one.
- Cycle length: hold one node in the loop and count one lap.
- Any
nextworks: digit squares for happy numbers,nums[i]for the duplicate number. - Palindrome list: middle, reverse the second half, compare, and restore if needed.