976. Longest Loop

A one-way tram network has n stops numbered 0 to n-1. From stop i the tram continues only to stop edges[i], or the line ends there when edges[i] == -1. A loop is a route that starts at some stop, follows the arrows, and returns to the same stop; its length is the number of distinct stops on it. A stop pointing at itself (edges[i] == i) is a loop of length 1.

Return the length of the longest loop in the network, or -1 if there is no loop at all.

Example 1

Input:
edges = [1,2,0,4,-1]
Output:
3
Explanation:

Nodes 0, 1, 2 form a cycle 0 to 1 to 2 to 0 of length 3; node 3 only leads into a dead end.

Example 2

Input:
edges = [3,3,3,0]
Output:
2
Explanation:

Nodes 0 and 3 point at each other, a cycle of length 2; nodes 1 and 2 lead into it.

Example 3

Input:
edges = [-1,-1]
Output:
-1
Explanation:

No node has an outgoing edge, so no loop exists and the answer is -1.

Constraints

  • 1 ≤ edges.length ≤ 105
  • -1 ≤ edges[i] ≤ n - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…