16/39
Part 4 of 7 · Cycles and meeting pointsLearn and do

Find a cycle, and the node where it starts

A list that loops is the classic two-speed question. Finding that it loops is the first half. Finding the node where the loop starts is the second.

The seen-set from the hash-maps lesson answers it first: walk, and if a node is already in the set, the list loops.

def has_cycle_set(head):
    seen, node = set(), head
    while node is not None:
        if node in seen:
            return True
        seen.add(node)
        node = node.next
    return False

A node in a set is keyed by identity, since Node defines no __eq__ of its own. That's O(n) time and O(n) memory.

Two pointers do it in O(1) memory. This is Floyd's cycle detection, often called the tortoise and the hare:

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


def looped(n, back_to):
    nodes = [Node(v) for v in range(n)]
    for a, b in zip(nodes, nodes[1:]):
        a.next = b
    nodes[-1].next = nodes[back_to]
    return nodes[0]


print(has_cycle(looped(8, 3)), has_cycle(linked([1, 2, 3])))
True False

looped(8, 3) makes nodes 0 to 7, and node 7 points back at node 3. Here are the two pointers on it, step by step:

head = looped(8, 3)
slow = fast = head
step = 0
while True:
    slow, fast = slow.next, fast.next.next
    step += 1
    print(f"step {step}: slow on {slow.val}, fast on {fast.val}")
    if slow is fast:
        break
Predict

looped(8, 3): nodes 0 to 7, and 7 points back at 3. slow moves one node a step and fast two. On which node do they meet?

Pick one to see what it prints.
Pick an answer above to see the rest