Linked List Cycle

EasyArrayLinked List

Description

You are given an integer array next where next[i] is the index of the node that node i points to, or -1 if node i has no next pointer. You are also given an integer head representing the starting index. Return true if following the next pointers from head eventually leads back to a previously visited node (i.e., there is a cycle), or false if the traversal reaches a node with next[i] == -1.

Examples

Input:next = [1, 2, 0, -1], head = 0
Output:true
Explanation:

Starting at index 0: 0 -> 1 -> 2 -> 0 (cycle detected).

Input:next = [1, -1], head = 0
Output:false
Explanation:

Starting at index 0: 0 -> 1 -> null. No cycle.

Input:next = [0], head = 0
Output:true
Explanation:

Node 0 points to itself, forming a cycle.

Constraints

  • 1 <= next.length <= 10^4
  • -1 <= next[i] < next.length
  • 0 <= head < next.length
  • next[head] != head is not guaranteed (self-loops are valid)

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!