Fast & Slow Pointers

Data Structures & Algorithms · Array Techniques · Intermediate · 20 min

Detect a loop, find the middle and find where a loop begins in a linked list with two pointers and O(1) extra memory.

A tortoise and a hare race along a path. If the path is a straight road, the hare reaches the end first. If the path bends back into a circle, the hare laps the tortoise and taps it on the shoulder.

The idea in everyday words

Two friends jog on a running track, one twice as fast as the other. On a straight road the fast one simply finishes and leaves. On a circular track the fast one is guaranteed to catch up from behind and pass the slow one, no matter where they started. You can tell which kind of track you are on just by checking whether they ever meet.

Two pointers, two speeds

A linked list is a chain of nodes, where each node only knows the next node. You cannot jump to the middle or ask "how long are you?". You can only walk.

The fast & slow pointer trick (also called tortoise and hare) walks two pointers through the same list:

  • slow moves 1 node per step.
  • fast moves 2 nodes per step.

That speed difference gives you information for free:

When fast... You learn
reaches the end (None) there is no loop
lands on the same node as slow there is a loop
is at the end, slow is... exactly in the middle

All of this uses O(1) extra memory: just two variables.

Floyd's cycle detection: why they must meet

The naive way to detect a loop: remember every node you have visited in a set, and stop when you see one twice. That works, but it costs O(n) memory.

Floyd's idea uses two pointers instead:

def 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 False

Why can't the hare jump over the tortoise? Once both are inside the loop, think of the hare as chasing the tortoise. Each step the hare gains exactly 1 node (it moves 2, the tortoise moves 1). A gap of 5 becomes 4, 3, 2, 1, 0. It shrinks one at a time, so it must hit 0. They meet within one lap.

Why check fast and fast.next? The hare takes two hops, so both the next node and the one after must exist. Forgetting this is the most common crash.

Finding the middle in one pass

When fast reaches the end, slow has walked half as far, so it is in the middle.

[1, 2, 3, 4, 5]: slow visits 1, 2, 3 while fast visits 1, 3, 5. Middle = 3.

[1, 2, 3, 4, 5, 6]: slow ends on 4, the second of the two middles. If you want the first middle, loop while fast.next and fast.next.next.

The same "two pointers with a gap" idea finds the k-th node from the end: move one pointer k steps ahead first, then move both by 1 until the leader hits the end.

This is used in merge sort on a linked list (split at the middle) and palindrome linked list (reverse the second half, compare).

Where does the loop start?

After the pointers meet, put a new pointer p at the head and move p and slow 1 step at a time. The node where they meet is the loop entrance.

Why does that work? Call the distance from the head to the entrance a, the loop length c, and the distance from the entrance to the meeting point b.

  • Slow walked a + b steps. Fast walked twice that: 2(a + b).
  • Fast's extra distance, a + b, was made of whole laps of the loop. So a + b is a multiple of c.
  • Starting at the meeting point (b into the loop), walking a more steps puts you at a + b into the loop, which is a whole number of laps: the entrance.
  • p also reaches the entrance after a steps from the head. So they arrive together.

Tiny check: 3 → 2 → 0 → -4 → (back to 2). Here a = 1, c = 3. They meet at -4 (b = 2), and a + b = 3 = one lap. Walking 1 step from the head and from -4 both lands on 2. ✓

Not just linked lists

Any process "from x, go to f(x)" is secretly a linked list. If it can repeat, fast and slow pointers can find the loop.

  • Happy number: replace n by the sum of the squares of its digits. 19 → 82 → 68 → 100 → 1, so 19 is happy. For an unhappy number the sequence loops forever (it never reaches 1). Run slow = f(n) and fast = f(f(n)) until they meet, then check whether they met at 1.
  • Find the duplicate number: in an array of n + 1 values from 1..n, treat i → nums[i] as a "next" link. The duplicate value is the loop entrance. O(1) memory, without changing the array.
def is_happy(n):
    f = lambda x: sum(int(d) ** 2 for d in str(x))
    slow, fast = n, f(n)
    while fast != 1 and slow != fast:
        slow, fast = f(slow), f(f(fast))
    return fast == 1

print(is_happy(19), is_happy(2))  # True False

Step by step

  1. Start:

    List: 3 → 2 → 0 → -4 → (back to 2). Index 0..3, the tail links to index 1. slow = fast = node 0 (value 3).

  2. Step 1:

    slow moves to 2 (index 1). fast jumps two: to 0 (index 2). Different nodes.

  3. Step 2:

    slow → 0 (index 2). fast → -4 → 2, landing on index 1. Fast has already gone round the loop once.

  4. Step 3:

    slow → -4 (index 3). fast → 0 → -4 (index 3). Same node: there is a loop.

  5. Phase 2 begins:

    Put p at the head (index 0). Keep slow at the meeting point (index 3). Now both move 1 step at a time.

  6. Phase 2, step 1:

    p → index 1. slow → follows -4's link back to index 1. They meet.

  7. Answer:

    The loop starts at index 1 (value 2). Total memory used: three pointers, no set of visited nodes.

Code example

class Node:
    def __init__(self, val):
        self.val, self.next = val, None

def make(values, loop_to=-1):
    nodes = [Node(v) for v in values]
    for a, b in zip(nodes, nodes[1:]):
        a.next = b
    if loop_to >= 0:
        nodes[-1].next = nodes[loop_to]
    return nodes[0]

def middle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    return slow.val

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False

def is_happy(n):
    f = lambda x: sum(int(d) ** 2 for d in str(x))
    slow, fast = n, f(n)
    while fast != 1 and slow != fast:
        slow, fast = f(slow), f(f(fast))
    return fast == 1

print("middle of 1..5:", middle(make([1, 2, 3, 4, 5])))
print("middle of 1..6:", middle(make([1, 2, 3, 4, 5, 6])))
print("cycle?", has_cycle(make([3, 2, 0, -4], 1)), has_cycle(make([1, 2, 3])))
print("happy 19?", is_happy(19), "happy 2?", is_happy(2))

Complexity

  • Time: O(n): with no loop the hare reaches the end in n/2 steps; with a loop they meet within one lap of the tortoise entering it, and phase 2 takes at most n more steps
  • Space: O(1): only a few pointer variables, no set of visited nodes

Interview tips

  • Mention the hash-set solution first (O(n) memory), then offer Floyd's as the O(1) memory upgrade. That shows you know the trade-off.

  • Be ready to explain WHY they meet: inside the loop the gap shrinks by exactly one node per step, so it cannot be skipped.

  • For 'find the start of the cycle', sketch the a / b / c distances. Interviewers love seeing you derive it instead of reciting it.

  • Always say your loop guard out loud: 'while fast and fast.next'. It shows you thought about even and odd lengths.

  • Follow-ups: length of the loop (keep one pointer still, count steps until the other returns), find the duplicate number, palindrome linked list.

Challenge: Where Does the Loop Begin?

You are given a linked list as values (the node values, in order) and pos: the index of the node that the last node links back to. pos = -1 means there is no loop.

Build the list, then return the index of the node where the loop begins, or -1 if there is no loop. Use O(1) extra memory (no visited set).

Example: cycle_start([3, 2, 0, -4], 1) → 1 (3 → 2 → 0 → -4 → back to 2)

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Array Techniques

Previous: Arrays & Two Pointers · Next: Sliding Window