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.

See it run

Two pointers walk the same chain at speeds 1 and 2: they meet if it loops, and slow sits in the middle when fast runs out.

Operations

Detect a cycle

Floyd's algorithm: slow moves one node, fast moves two. If they ever land on the same node the list loops; if fast reaches None it does not.

Step 1 of 9

A list shaped like the letter rho

123456

tail a

1 · 2

loop L

3 · 4 · 5 · 6

1 → 2 → 3 → 4 → 5 → 6, and 6 points back to 3. A plain walk would circle forever. The tail before the loop has a = 2 nodes (1, 2); the loop has L = 4 nodes (3, 4, 5, 6).

Step 1: A list shaped like the letter rho

def has_cycle(head):    slow = fast = head    while fast and fast.next:        slow = slow.next          # 1 step        fast = fast.next.next     # 2 steps        if slow is fast:            return True    return False
Time
O(n)
Space
O(1)
visited set
O(n) time, O(n) space
steps to meet
at most a + L

Compare nodes with `is`, never values: two different nodes can hold the same number.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Checking fast.next before fast

    critical

    When fast is already None, fast.next raises AttributeError. The None check has to come first so and can short-circuit.

    Wrong
    while fast.next and fast:    slow, fast = slow.next, fast.next.next
    Right
    while fast and fast.next:    slow, fast = slow.next, fast.next.next
  • Comparing values instead of nodes

    critical

    Two different nodes can store the same value, so 5 → 7 → 5 → 9 → 5 → None is reported as a cycle (slow and fast both land on a 5 after two steps). A cycle means the same node object, so compare identity.

    Wrong
    if slow.val == fast.val:    return True
    Right
    if slow is fast:    return True
  • Testing for a meeting before moving

    major

    Both pointers start on the head, so a check at the top of the loop is True on the very first pass and every list looks cyclic. Move first, then compare.

    Wrong
    slow = fast = headwhile fast and fast.next:    if slow is fast:        return True          # True immediately    slow, fast = slow.next, fast.next.next
    Right
    slow = fast = headwhile fast and fast.next:    slow, fast = slow.next, fast.next.next    if slow is fast:        return True
  • Moving fast two steps in phase 2

    major

    The proof that both pointers reach the entrance together needs both to cover exactly a nodes. At speeds 1 and 2 they meet somewhere in the loop, not necessarily at its start.

    Wrong
    slow = headwhile slow is not fast:    slow, fast = slow.next, fast.next.next
    Right
    slow = headwhile slow is not fast:    slow, fast = slow.next, fast.next
  • Different heads in the two phases (find the duplicate)

    critical

    Starting phase 1 at nums[0] but phase 2 at index 0 shifts one pointer by a hop, and the pointers can circle the loop forever without meeting. Start both phases at index 0.

    Wrong
    slow = fast = nums[0]...                          # phase 1slow = 0                     # off by one hop
    Right
    slow = fast = 0...                          # phase 1slow = 0
  • Making the hare run three steps

    minor

    At speed 3 the gap shrinks by 2 per step. On a loop of even length with an odd gap it skips 0 forever, so the pointers never meet. Speed 2 shrinks the gap by exactly 1 and cannot skip.

    Wrong
    fast = fast.next.next.next     # gap - 2 each step
    Right
    fast = fast.next.next          # gap - 1 each step

Interview tips

  • How to explain it

    • Two pointers at speeds 1 and 2 on the same chain. In a loop the gap closes by one node per step, so they must meet.
    • To find the entrance: a + b = kL, so a = kL − b. Reset one pointer to the head and step both by one.
    • O(n) time and O(1) space, versus a visited set at O(n) space.
  • Spot it in the wild

    • Linked list cycle, cycle start, cycle length.
    • Middle node, palindrome list, reorder list, splitting for merge sort.
    • Any f(x) sequence that must repeat: happy number, find the duplicate number, Pollard's rho.
  • Memory tricks

    • RACE: Run both from the start, Advance at speeds 1 and 2, Check if they meet, End when fast hits None.
    • Runners on a circular track: the faster one always laps the slower one.
    • Phase 2 is a walk, not a race: both at speed 1.
  • Watch out

    • Check fast before fast.next.
    • Compare nodes with is, not values.
    • Move first, compare second, or the head counts as a meeting.