Find the cycle start
Challenge · Write code · about 20 min
A singly linked list may end in a loop: the tail points back to an earlier node instead of null. Return the index of the node where the loop begins, or -1 if there is no loop. Use O(1) extra space.
Tests describe the list as values plus pos, the index the tail links back to (-1 for none). The starter's linkTail(head, pos) builds that loop; call it first and do not use pos otherwise.
Example 1
Input:
[[3,2,0,-4],1]
Output:
1
Example 2
Input:
[[1,2],-1]
Output:
-1
pos -1: the tail points to null, so there is no loop.
Constraints
- 0 ≤ number of nodes ≤ 5,000
- -1 ≤ pos < number of nodes
- -100,000 ≤ node value ≤ 100,000
Learn the idea first: Linked list techniques: reverse, middle, merge, detect a cycle, a visual lesson.
More Linked list techniques: reverse, middle, merge, detect a cycle problems
- Reverse a list Warm-up
- Middle node Warm-up
- Merge two sorted lists Standard
- Palindrome list Standard
- Trace a list reversal Standard