Does this linked list loop? Answer with O(1) extra memory
Question
Each node of a singly linked list has val and next. Write has_cycle(head). Return True if following next from head ever brings you back to a node you already passed. Return False if you reach None. Use O(1) extra memory, so no set of visited nodes.
3 → 8 → 5 → 1 → 6, and the node 6 points back to the node 5:True.3 → 8 → 5, thenNone:False.- An empty list,
head is None:False.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def has_cycle(head): ...
Show hints (3)
- "TWO SPEEDS"
Picture two runners on a track. If the track is a loop, the faster runner laps the slower one. If the track has an end, the faster runner reaches it first.
- "MOVE, THEN COMPARE"
Start both pointers at
head. Move first, then compare. If you compare before the first move, they are already equal, and every list of two or more nodes returnsTrue. - "THE LOOP GUARD"
Loop while
fast is not None and fast.next is not None. Moveslowone node andfasttwo, then returnTrueifslow is fast. After the loop, returnFalse.
Show checked explanation
Use two pointers, both starting at head. On each step, slow moves one node and fast moves two. If fast reaches None, there is no loop. If the two pointers land on the same node, there is a loop. This is Floyd's algorithm: O(n) time and O(1) extra memory.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next 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 five = Node(5, Node(1, Node(6))) five.next.next.next = five # 6 points back to 5 print(has_cycle(Node(3, Node(8, five)))) print(has_cycle(Node(3, Node(8, Node(5))))) print(has_cycle(None))
True False False
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Run it on 3 → 8 → 5 → 1 → 6, where 6 points back to 5. Both pointers start at 3:
| step | slow | fast |
|---|---|---|
| start | 3 | 3 |
| 1 | 8 | 5 |
| 2 | 5 | 6 |
| 3 | 1 | 1 |
After step 3, both pointers are on the node 1, so the list loops. Two nodes come before the loop (3 and 8), and the loop holds three (5, 1 and 6). The pointers met at 1, not at 5, where the loop starts.
Why must they meet? Once both pointers are inside the loop, fast gets exactly one node closer to slow on every step. If it is 2 nodes behind, it is 1 behind after the next step, then 0. Because the gap closes by one, fast can't jump over slow. Without a loop, fast reaches the end first, and the function returns False.
Both pointers start on the same node, so compare only after you move. The loop guard fast is not None and fast.next is not None makes fast.next.next always safe.
With n nodes, slow moves at most n times before the pointers meet or fast hits the end. That is O(n) time. You store only two references, so the extra memory is O(1).
Common mistakes
- Comparing
slow is fastbefore the first move. Both start athead, so every list of two or more nodes returnsTrue, even3 → 8 → 5. - Writing only
while fast:. On a one-node list,fast.nextisNone, sofast.next.nextraisesAttributeError. - Comparing values with
slow.val == fast.val. The list2 → 2 → 2has no loop, but after one step both pointers hold a 2, so you returnTrue. - Treating the meeting node as the start of the loop. In the example, the pointers meet at 1, but the loop starts at 5. Finding the start takes a second pass.
Follow-up questions
- "Where does the loop start?" Put one pointer back at
headand leave the other at the meeting node. Move both one node at a time. They meet where the loop starts. In the example,3 → 8 → 5and1 → 6 → 5both reach 5 after two steps. It works becausefastwalked twice as far asslow, and the extra distance is a whole number of laps. - "How long is the loop?" Keep one pointer on the meeting node. Walk the other around the loop and count the steps until it comes back. In the example,
1 → 6 → 5 → 1takes 3 steps. - "Why not just keep a set of visited nodes?" That works, and it is simpler: add each node to a set and stop when you see one again. Plain objects hash by identity, so equal values don't clash. It also finds the loop start directly. The cost is O(n) extra memory, which the two pointers avoid.
What a strong answer covers
Checks for None before each move and compares only after moving. Explains why the fast pointer can't skip over the slow one. Says the meeting node need not be the loop start, and knows the second pass that finds it.
Open in interactive practice deck →