Linked List Cycle - Problem
Imagine you're following a chain of connected nodes, where each node points to the next one. But what if this chain secretly loops back on itself? ๐
Given the head of a linked list, your mission is to detect if there's a cycle - meaning you could theoretically follow the next pointers forever and end up visiting the same node again.
What makes this tricky? You can't see the entire structure at once, and you don't know where the cycle might begin (if it exists). You can only follow the next pointers one by one.
Return true if there's a cycle, false otherwise.
Note: The parameter pos mentioned in examples is just for illustration - it's not actually passed to your function.
Input & Output
example_1.py โ Cycle exists
$
Input:
head = [3,2,0,-4], pos = 1
โบ
Output:
true
๐ก Note:
There is a cycle where the tail connects back to the 1st node (0-indexed). The last node (-4) points back to the second node (2), creating a loop.
example_2.py โ Simple cycle
$
Input:
head = [1,2], pos = 0
โบ
Output:
true
๐ก Note:
There is a cycle where the tail connects back to the 0th node. The second node (2) points back to the first node (1).
example_3.py โ No cycle
$
Input:
head = [1], pos = -1
โบ
Output:
false
๐ก Note:
There is no cycle in the linked list. A single node with no next pointer cannot form a cycle.
Constraints
- The number of nodes in the list is in the range [0, 104]
- -105 โค Node.val โค 105
- pos is -1 or a valid index in the linked-list
- Follow up: Can you solve it using O(1) memory?
Visualization
Tap to expand
Understanding the Visualization
1
Start the Race
Both runners start at the same position (head of linked list)
2
Different Paces
Slow runner takes 1 step, fast runner takes 2 steps each turn
3
Two Outcomes
Either fast runner reaches finish line (no cycle) or catches slow runner (cycle found)
Key Takeaway
๐ฏ Key Insight: Floyd's algorithm elegantly solves cycle detection with constant space by leveraging the mathematical property that two pointers at different speeds will always meet in a cycle.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code