Linked List Cycle II - Problem
Imagine you're following a series of connected rooms, where each room has an arrow pointing to the next room. You suspect there might be a loop - a sequence of rooms that eventually leads back to a room you've already visited!
Given the head of a linked list, your mission is to find the exact node where the cycle begins. If there's no cycle, return null.
Important: You cannot modify the linked list structure, and you must solve this efficiently!
Example: If you have a linked list 3 → 2 → 0 → -4 and the last node -4 points back to node 2, then the cycle begins at node 2.
Input & Output
example_1.py — Basic Cycle
$
Input:
head = [3,2,0,-4], pos = 1
›
Output:
Node with value 2
💡 Note:
The linked list is 3 → 2 → 0 → -4, and the tail connects back to the node with value 2 (at position 1). The cycle starts at the second node.
example_2.py — Self Loop
$
Input:
head = [1,2], pos = 0
›
Output:
Node with value 1
💡 Note:
The linked list is 1 → 2, and the tail connects back to the first node (position 0). The cycle starts immediately at the head.
example_3.py — No Cycle
$
Input:
head = [1], pos = -1
›
Output:
null
💡 Note:
There is only one node and no cycle exists (pos = -1 indicates no cycle), so we return null.
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) constant memory?
Visualization
Tap to expand
Understanding the Visualization
1
Start the Race
Both runners start at the same point. Slow runner takes 1 step, fast runner takes 2 steps.
2
They Meet!
If there's a loop, the fast runner will eventually catch up to the slow runner inside the loop.
3
Find the Loop Start
Reset one runner to start. Now both move at same speed. Where they meet is the loop beginning!
Key Takeaway
🎯 Key Insight: Floyd's algorithm leverages the mathematical relationship between pointer speeds and cycle geometry to find the cycle start in optimal time and space complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code