Linked List Cycle II - Problem
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Input & Output
Example 1 — Cycle Exists
$
Input:
head = [3,2,0,-4], pos = 1
›
Output:
Node with value 2
💡 Note:
The cycle begins at node with value 2 (index 1). The last node (-4) points back to the node with value 2.
Example 2 — Self Loop
$
Input:
head = [1,2], pos = 0
›
Output:
Node with value 1
💡 Note:
The cycle begins at the head node (value 1). The second node points back to the first node.
Example 3 — No Cycle
$
Input:
head = [1], pos = -1
›
Output:
null
💡 Note:
There is only one node and no cycle exists, so return null.
Constraints
- The number of the 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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Linked list with potential cycle
2
Process
Detect cycle and find starting point
3
Output
Return the cycle start node or null
Key Takeaway
🎯 Key Insight: Floyd's algorithm mathematically guarantees that after detecting a cycle, resetting one pointer to head and moving both at same speed will make them meet exactly at the cycle start.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code