Reading preferences
Concept

Fast and Slow Pointers

Detect a linked-list cycle by moving at different speeds.

python, pointers, linked lists, cycles

Different speeds reveal a loop

A linked list is a chain of nodes; each node points to the next or to None. If a link returns to an earlier node, traversal never reaches the end. Move one reference one link at a time and another two links at a time.

Python illustration

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

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

a, b, c = Node("A"), Node("B"), Node("C")
a.next, b.next, c.next = b, c, b
print(has_cycle(a))

Prepared output: True. C points back to B.

See the reasoning

Follow two speeds

Track node identity in one cyclic list. This is a prepared demonstration, not live code execution.

Start at A

A → B → C → B
  1. SlowACurrent focus
  2. FastA

Both references start at the head; equality is checked after moving.

Why it works and its limits

If a finite chain ends, fast reaches None. In a cycle, once both references are inside it, fast gains one position per iteration modulo the cycle length and eventually meets slow. Compare node identity, not node values. For n reachable nodes, time is O(n), extra space O(1). The method assumes stable links and identifies the presence of a cycle, not its entry point.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. How do the pointers move?
2. Why compare nodes with is?
3. What does reaching a missing next node establish?
4. What extra space do the two pointers use?

References and further reading