Does the list loop back on itself? Send a tortoise and a hare down it: if there's a cycle, the faster runner must catch the slower one.
▼The problem
LeetCode 141 (Easy). Given the head of a linked list, return true if the list has a cycle (some node's next leads back to an earlier node).
Example (the original's): six nodes 1 → 2 → 3 → 4 → 5 → 6, and node 6 points back to node 3.
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 # they met
return False # hare hit the endTRY IT ON LEETCODE ▶The solution
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 # they met
return False # hare hit the endTranscript
Linked List Cycle. You're given the head of a linked list, where each node points to the next. Does the list end, or does it loop back on itself?
Here are six nodes. The last one doesn't end the list: it points back to node three. So a walk along the arrows goes three, four, five, six, three again, round and round forever.
You can't just walk until the end, because a loop has no end. The simple way: remember every node you visit in a set. Reach one that's already there, and you've found a cycle. It works, but the set needs memory for every node.
Floyd's trick uses no memory, just two runners. The tortoise moves one node per step. The hare moves two. If the list ends, the hare gets there first. If there's a loop, both end up going round it, and each step the hare gains exactly one node. The gap shrinks by one, so the hare can't skip past. It must land on the tortoise.
In code, start both at the head. While the hare can still jump two, move the tortoise once and the hare twice. If they're on the same node, return true. If the loop ends, the hare reached the end, so return false.
Let's race. Step one: tortoise on two, hare on three. Step two: tortoise on three, hare on five. Step three: the hare runs to six and follows the link back to three, while the tortoise reaches four. Step four: the tortoise moves to five, and the hare jumps to five. They meet: a cycle.
Now cut the link back. The hare jumps to three, then five, then off the end. The loop stops: no cycle.
Once both are in the loop, the gap is less than a lap and shrinks by one each step, so they meet within one lap. That's order n time. Just two pointers, so the space is order one.
One slow, one fast, no memory. That's Linked List Cycle.