Linked List Cycle II
Medium
LC #142
fast & slow pointerscycle detectionNot attempted yet
Given the head of a linked list, return the index of
the node where the cycle begins (0-based, counting from
head), or -1 if the list has no cycle.
Return an index rather than the node, so the answer is a
plain number. Each example's pos is the index that the
last node's next points back to. Your function receives
only head.
Example 1
Input: head = [3,2,0,-4], pos = 1
Output: 1
Example 2
Input: head = [1,2], pos = 0
Output: 0
Example 3
Input: head = [1], pos = -1
Output: -1
Constraints
- 0 ≤ number of nodes ≤ 10⁴
- -10⁵ ≤ Node.val ≤ 10⁵
posis-1or a valid index
Can you solve it with O(1) extra space?