Longest Cycle in a Graph Problem
Description
LeetCode Problem 2360.
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.
Return the length of the longest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same node.
Example 1:

Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.
Example 2:

Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
n == edges.length2 <= n <= 10^5-1 <= edges[i] < nedges[i] != i
Solution
Approach: Walk from Every Unvisited Node
Every node has at most one outgoing edge, so from any start the walk either ends at a node with no edge (-1), reaches a node visited earlier, or runs into itself.
For each unvisited node, walk along the edges, marking nodes visited and recording the path. The walk stops when it reaches -1 or an already visited node j. If j is on the path we just recorded, the nodes from j to the end of the path form a new cycle: its length is the path length minus the position of j. If j was visited in an earlier walk (or the walk ended at -1) there is no new cycle. Keep the longest cycle length, or -1 if there is none.
Every node is visited once, so the whole graph is processed in linear time.
Complexity: O(n) time and O(n) extra space.
class Solution:
def longestCycle(self, edges: List[int]) -> int:
n = len(edges)
vis = [False] * n
ans = -1
for i in range(n):
if vis[i]:
continue
j = i
cycle = []
while j != -1 and not vis[j]:
vis[j] = True
cycle.append(j)
j = edges[j]
if j == -1:
continue
for k, v in enumerate(cycle):
if v == j:
ans = max(ans, len(cycle) - k)
break
return ans