n nodes numbered 0 to n - 1, and each node has at most one outgoing directed hop. The hops are given by an array next_hop of length n: from node i you can hop to node next_hop[i], and next_hop[i] == -1 means node i has no hop.
A **loop** is a path of hops that comes back to the node where it started. Return the number of nodes in the longest loop, or -1 if there are no loops.next_hop=[1, 2, 0, 2, -1] → 3
The loop 0 → 1 → 2 → 0 has three nodes. Node 3 leads into it without being part of it, and node 4 has no way out.
next_hop=[-1, 0, 1] → -1
The chain 2 → 1 → 0 stops at node 0, so there is no loop and the answer is -1.
next_hop=[1, 0, 3, 4, 5, 2] → 4
There are two loops: 0 ⇄ 1 of length 2 and 2 → 3 → 4 → 5 → 2 of length 4. The longest is 4.
next_hop=[1, 2, 0, 2, -1]
3
Run checks the first 3 tests in your browser. Submit checks all 73 tests on the server, hidden ones included.