Ctrl K

Longest Loop of Hops

Hard
A network has 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.
Example 1
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.

Example 2
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.

Example 3
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.

Constraints
  • 2 ≤ n ≤ 10⁵, n = len(next_hop)
  • -1 ≤ next_hop[i] < n
  • next_hop[i] ≠ i
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLetter Order From a Dictionary HardLongest Uphill Walk HardTask Plan by Teams HardUphill-Only Walks HardSpread the News to Everyone Hard
loading Python…
Input
next_hop=[1, 2, 0, 2, -1]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 73 tests on the server, hidden ones included.