Detect a cycle
We'll cover the following
Decide whether a linked list loops back on itself, and find where the loop starts.
Watch it run
Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.
slow/fast10
21
32
43
54
65
76
87
98
109
1110
1211
1312
1413
1514
1615
slow moves 1 step, fast moves 2. The tail of the list links back to node 6.
1 / 18
The idea
Complexity
| Time | Space | Why |
|---|---|---|
O(n) | O(1) | Inside a loop, fast gains one node per step, so they meet within one lap. |
In Python
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast: return True
return FalseSummary: say it in the interview
- Send a slow pointer (1 step) and a fast pointer (2 steps). In a loop the fast one laps the slow one and they must meet. With no loop, fast simply falls off the end. No extra memory is needed.
- Time O(n), space O(1). Inside a loop, fast gains one node per step, so they meet within one lap.