Detect a Linked-List Cycle
Problem statement
A linked list is encoded by nextIndex: node i points to node nextIndex[i], and -1 marks the end. Traversal starts at node 0.
Return whether the reachable chain contains a cycle. An empty array represents an empty list.
Function
hasCycle(nextIndex: int[]) → booleanExamples
Example 1
nextIndex = [-1]return = falseCase 1 exercises the documented deterministic contract.
Example 2
nextIndex = [1,2,-1]return = falseCase 2 exercises the documented deterministic contract.
Example 3
nextIndex = [1,2,0]return = trueCase 3 exercises the documented deterministic contract.
Constraints
0 <= nextIndex.length <= 200000.- Every value is
-1or a valid node index.