Learning Outcome
After this lesson, you should be able to explain why fast and slow pointers meet if a linked list contains a cycle.
Problem Statement
Given the head of a linked list, return true if the list has a cycle. A cycle means a node's next pointer points back to an earlier node.
| Input shape | Output | Why |
|---|---|---|
3 -> 2 -> 0 -> -4, where -4 points back to 2 | true | The list loops forever. |
1 -> 2 -> null | false | The list ends normally. |
Brute Force Approach
Store every visited node in a set. If the same node appears again, there is a cycle.
This is easy and correct, but it uses O(n) extra space.
Optimized Approach
Use Floyd's cycle detection. Move slow one step and fast two steps. If there is a cycle, fast eventually catches slow. If there is no cycle, fast reaches null.
Exact Pseudocode
slow = head
fast = head
while fast is not null and fast.next is not null:
slow = slow.next
fast = fast.next.next
if slow == fast:
return true
return false
Reference Code
class Solution:
def hasCycle(self, head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return FalseSample Dry Run
| Step | slow | fast | Result |
|---|---|---|---|
| Start | 3 | 3 | Begin |
| 1 | 2 | 0 | Not equal |
| 2 | 0 | 2 | Not equal |
| 3 | -4 | -4 | Equal, cycle exists |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | The pointers traverse at most linear distance before ending or meeting. |
| Space | O(1) | No visited set is needed. |
Edge Cases
- Empty list.
- Single node with no cycle.
- Single node pointing to itself.
Interview Checklist
- Check
fastandfast.nextbefore moving two steps. - Compare node references, not values.
- Explain why fast catches slow inside a cycle.
FAQs
Why do fast and slow meet in a cycle?
Inside the cycle, fast gains one node on slow each iteration, so the gap eventually becomes zero.
Why compare nodes instead of values?
Different nodes can have the same value. A cycle is about references, not values.
What is the core pattern?
Floyd's fast and slow pointer cycle detection.