Detect a Cycle in a Linked List
Problem statement
Determine whether a singly linked list contains a cycle reachable from its head. Return true if repeatedly following next links ever visits the same node again; otherwise return false.
The finite input preserves node identity with indices. next[i] is the index of node i's successor, or -1 for null. head is the first node index, or -1 for an empty list. Different indices represent different nodes even when their values would match. No node values are needed to detect a cycle.
Only nodes reachable from head belong to the list being queried; ignore disconnected nodes. Links may point to any valid node index, including the same node. For this exercise, assume the supplied indices are valid and do not change.
Function
hasCycle(next: int[], head: int) → booleanExamples
Example 1
next = [1,2,1]head = 0return = trueThe successor walk revisits node 1, so the reachable list has a cycle.
Example 2
next = [1,2,-1]head = 0return = falseThe successor walk reaches null without repeating a node.
Example 3
next = []head = -1return = falseAn empty list has no reachable cycle.
Constraints
0 <= next.length <= 100000.- Every successor is
-1or an index innext. headis-1or a valid node index; an empty array hashead = -1.