AlgoViz

Fast and slow pointers

medium 20 min

Two 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

0:00 / 6:08

The tortoise and the hare in 75 seconds

1:15Reel coming soon

How it works

Step through the idea, or press Play.

Step 1 of 3

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: O(1)O(1) extra space, O(n)O(n) 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 aa nodes leading into a loop of LL nodes.

The rho shape used on this page

Tail a=2a = 2 (nodes 1 and 2), loop L=4L = 4 (nodes 3 to 6). Node 3 is the only node with two arrows coming in.
What happensWhat it meansWhere slow is
fast or fast.next becomes NoneThe list ends: no cycleThe middle node
slow is fast after a stepThe list loopsSomewhere inside the loop, bb nodes past the entrance
One loop, two possible endings. Every pattern on this page starts from one of these two rows.

The proof

Why the hare always catches the tortoise

Once slow enters the loop (after aa steps), fast is already somewhere in it. Let dd be how many nodes fast must still cover to land on slow, with 0≤d<L0 \le d < L. Each step fast moves 2 and slow moves 1, so fast gains exactly one node.

The gap shrinks by one per step

dt+1=dt−(2−1)=dt−1⇒dt=d0−t=0 when t=d0≤L−1d_{t+1} = d_t - (2 - 1) = d_t - 1 \quad\Rightarrow\quad d_t = d_0 - t = 0 \text{ when } t = d_0 \le L - 1
The gap counts down 2, 1, 0 in the example. Because it drops by exactly one, it cannot jump over zero: the pointers land on the same node, they do not pass each other.

So the whole run is linear

steps  ≤  a⏟reach the loop+L−1⏟close the gap  <  a+L=n⇒O(n) time, O(1) space\text{steps} \;\le\; \underbrace{a}_{\text{reach the loop}} + \underbrace{L - 1}_{\text{close the gap}} \;<\; a + L = n \quad\Rightarrow\quad O(n) \text{ time, } O(1) \text{ space}
Slow visits each node at most once before the meeting. Fast may go round a short loop many times, but it takes only two hops per step, so the total work is still O(n)O(n).

Pattern 1

Detecting a cycle with Floyd's algorithm

Floyd's cycle detection

Move first, then compare. Checking before moving would report a meeting at the head every time.
Python
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]))   # True
Build the rho list from the diagram and a straight one, then test both.
Edit and run it in your browser

Floyd's two pointers

  • O(1)O(1) extra space
  • Works on any next function, not just lists
  • Also yields the meeting point for phase 2

A visited set

  • O(n)O(n) 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: aa from the head to the entrance, bb from the entrance to the meeting point, LL 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 k≥1k \ge 1 more.

The distance proof

2(a+b)=a+b+kL  ⇒  a+b=kL  ⇒  a=kL−b=(k−1)L+(L−b)2(a + b) = a + b + kL \;\Rightarrow\; a + b = kL \;\Rightarrow\; a = kL - b = (k - 1)L + (L - b)
Walking aa steps from the meeting point means L−bL - b steps to reach the entrance and then k−1k - 1 whole laps: you end on the entrance. Walking aa steps from the head also ends on the entrance. In the example a=2a = 2, b=2b = 2, L=4L = 4, k=1k = 1.

Phase 2: from meeting point to entrance

Both pointers cover exactly aa nodes, so they arrive together. In the duplicate-number problem k=2k = 2: fast laps a two-node loop twice.
StepslowfastNote
phase 1 end55met after 4 steps; slow walked 4, fast 8
reset15slow back to the head
126both move one
233meet at the entrance, after a=2a = 2 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 LL. In the example, from node 3: 4, 5, 6, 3 gives L=4L = 4.

Python
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 length
LL extra steps. Knowing LL also gives the tail length: a=n−La = n - L when the total node count nn is known.

Pattern 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

while fast and fast.next⇒⌊n2⌋while fast.next and fast.next.next⇒⌊n−12⌋\texttt{while fast and fast.next} \Rightarrow \left\lfloor \tfrac{n}{2} \right\rfloor \qquad \texttt{while fast.next and fast.next.next} \Rightarrow \left\lfloor \tfrac{n-1}{2} \right\rfloor
0-based indexes. For odd nn both give the true middle. For n=6n = 6 the first gives index 3 (the second middle) and the second gives index 2 (the first middle).
Listwhile fast and fast.nextwhile fast.next and fast.next.nextTypical use
1 2 3 4 533either
1 2 3 4 5 64 (second middle)3 (first middle)first: split for merge sort; second: LeetCode middle node
The second form needs a non-empty list, since it reads fast.next straight away.

Pattern 5

Happy numbers: a list you never build

Replace nn by the sum of the squares of its digits and repeat. nn is happy if this reaches 1, for example 19→82→68→100→119 \to 82 \to 68 \to 100 \to 1. 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 has d digits⇒next(n)≤81d,81d<10d−1 for d≥4  ⇒  values soon stay below 1000n \text{ has } d \text{ digits} \Rightarrow \text{next}(n) \le 81d, \qquad 81d < 10^{d-1} \text{ for } d \ge 4 \;\Rightarrow\; \text{values soon stay below } 1000
Big numbers shrink fast, and once below 1000 the next value is at most 81⋅3=24381 \cdot 3 = 243. Finitely many values means a repeat (pigeonhole), so every start ends in a loop: either 1→11 \to 1 or the unhappy loop below.

n = 2 is not happy

Every unhappy number falls into this same loop of eight. Floyd's pointers meet at 20 after 8 steps; for 19, fast reaches 1 on step 2.
Python
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]
Edit and run it in your browser

Pattern 6

Find the duplicate: an array as a linked list

An array of n+1n + 1 numbers, each between 1 and nn, must repeat some value. Find it without changing the array and in O(1)O(1) extra space. Read index ii 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

Index 3 and index 4 both hold 2, so two arrows enter node 2. Here a=3a = 3, L=2L = 2, the meeting point is 4 (b=1b = 1) and k=2k = 2: 3=2⋅2−13 = 2 \cdot 2 - 1.
ApproachTimeExtra spaceChanges the array?
Sort, then scan neighboursO(nlog⁡n)O(n \log n)O(1)O(1) or O(n)O(n)yes
Hash set of seen valuesO(n)O(n)O(n)O(n)no
Binary search on the value range (count values ≤ mid)O(nlog⁡n)O(n \log n)O(1)O(1)no
Floyd on the index graphO(n)O(n)O(1)O(1)no
Python
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]))   # 2
Edit and run it in your browser

Pattern 7

Palindrome linked list: middle, reverse, compare

Three passes, no extra list
  1. 1Find the middleslow and fast; slow stops on the middle
  2. 2Reverse the second halfflip next pointers from slow to the end
  3. 3Comparewalk head and the reversed half together
  4. 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.

Python
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])))         # False
Edit and run it in your browser

Choosing

When to reach for fast and slow pointers

Which variant do I need?

ProblemSignalKey insightTime / space
Linked list cycleslow is fastThey meet inside the loopO(n)O(n) / O(1)O(1)
Cycle startreset slow to heada=kL−ba = kL - b, both arrive togetherO(n)O(n) / O(1)O(1)
Cycle lengthwalk until backcount one lapO(n)O(n) / O(1)O(1)
Middle nodefast.next is Noneslow covered halfO(n)O(n) / O(1)O(1)
Happy numbersum of squared digitssame as cycle detectionO(log⁡n)O(\log n) / O(1)O(1)
Find the duplicatevalues 1 to nn in n+1n + 1 slotsduplicate is the loop entranceO(n)O(n) / O(1)O(1)
Palindrome listcompare ends of a singly listmiddle + reverse halfO(n)O(n) / O(1)O(1)

Use it when

  • Detecting cycles in lists or in any repeated function
  • Finding the middle in one pass and O(1)O(1) 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 with while fast and fast.next).
  • In a loop the gap closes by exactly one node per step, so they meet within LL steps of slow entering: O(n)O(n) time, O(1)O(1) space.
  • Cycle start: a=kL−ba = kL - b, 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 next works: digit squares for happy numbers, nums[i] for the duplicate number.
  • Palindrome list: middle, reverse the second half, compare, and restore if needed.

Sources