Problem 588113 · medium · Level 05 Advanced Algorithms & Graphs

Longest Cycle of Successors

graphs · directed graph · cycle detection · functional graph

A directed graph is given as a list nxt where every node i has at most one outgoing edge: nxt[i] is the node it points to, or -1 if it has none. Return the length (number of edges) of the longest directed cycle in the graph, or -1 if there is no cycle.

Examples

Input:  nxt = [1,2,3,1,3,-1]
Output: 3
Explanation: 1 -> 2 -> 3 -> 1 is a cycle of length 3. Nodes 0 and 4 lead into it but are not on it,
             and node 5 has no outgoing edge.

Input:  nxt = [-1,0,1,1]
Output: -1
Explanation: 3 -> 1 -> 0 and 2 -> 1 -> 0 both end at node 0, which has no outgoing edge.

Constraints

  • nxt[i] == i is allowed (a cycle of length 1).
  • Target O(n) time - every node must be walked at most once overall.

Goals

  • Detect directed cycles using per-walk timestamps
  • Avoid re-walking nodes that an earlier walk already covered
Starting Python…