Detect a Loop in a Linked List
Problem statement
A singly linked list is described by node indices. There are n = nextIndices.length allocated nodes, numbered 0 through n - 1. For each node i, nextIndices[i] is the index of its next node, or -1 when its next pointer is null.
The list starts at head. A head of -1 means an empty list, even if other nodes are allocated. Only nodes reachable by following next pointers from the head belong to the list; other allocated nodes do not affect the answer.
Return true if following next pointers from the head eventually revisits a node. Return false if it reaches null. Do not change any next pointer.
Function
hasCycle(nextIndices: int[], head: int) → booleanExamples
Example 1
nextIndices = [1,2,1]head = 0return = trueThe reachable path is 0 → 1 → 2 → 1. Node 1 is visited again, so the list has a cycle.
Example 2
nextIndices = [1,2,-1,3]head = 0return = falseThe reachable path is 0 → 1 → 2 → null. Node 3 points to itself, but it is not reachable from head 0 and does not make this list cyclic.
Example 3
nextIndices = []head = -1return = falseThe head is null, so there is no node to revisit.
Constraints
0 <= nextIndices.length <= 10^5.- Every element of
nextIndicesis-1or a valid node index. -1 <= head < nextIndices.length.