Fast and Slow Pointers

A Two Pointer variation where pointers move at different speeds. Perfect for cycle detection in Linked Lists.

Recognition

  • Cycle detection in a linked list or functional graph.
  • Finding a middle node in one pass.
  • Need O(1) space instead of a visited set.

When not to use it

Do not force this pattern when the input is unordered and hashing is enough.

Avoid coding the template before naming the invariant you need to preserve.

Logic template

Python

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

JavaScript

function hasCycle(head) {
  let slow = head, fast = head;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}

Typically better than the obvious O(N^2) approach; verify with the template.

  • Name what stays true after every move.
  • Track the exact condition that lets you discard work safely.

Worked example

Recognition drill

Identify the reusable state and the rule that advances it.

  1. Restate the goal in one sentence.
  2. Name the moving parts and what they represent.
  3. Write the loop invariant before coding.
  4. Trace one failing case that breaks a naive approach.

Result: You can explain when to reach for the pattern and when to abandon it.

Common pitfalls

  • Off-by-one updates on loop bounds.
  • Updating state after comparing instead of before.
  • Confusing “solved once” with pattern mastery.

Related practice problems