Problem · Linked List
Linked List Cycle Entry Node
Learn this problemProblem statement
A singly linked list is serialized by an integer array next. Node i points to node next[i]; a value of -1 means that node has no successor. Node 0 is the head, and every represented node is reachable by repeatedly following successors from the head before traversal stops or repeats a node.
If the list contains a cycle, return the zero-based index of the first node in that cycle. Otherwise, return -1.
Function
findCycleEntry(next: int[]) → intExamples
Example 1
next = [1,2,3,1]return = 1The traversal is 0 -> 1 -> 2 -> 3 -> 1. Node 1 is the first node in the cycle.
Example 2
next = [1,2,3,-1]return = -1The traversal reaches node 3 and then stops, so the list has no cycle.
Example 3
next = [0]return = 0The head points to itself, so node 0 is the cycle entry.
Constraints
1 <= next.length <= 2 * 10^5.- Every
next[i]is either-1or an integer from0throughnext.length - 1. - Every represented node is reachable from node
0before traversal stops or first repeats a node.