Longest Cycle in a Graph

hard graph dfs topological sort

Problem

In a directed graph where each node has at most one outgoing edge (encoded by edges[i], or -1), return the length of the longest cycle, or -1 if none exists.

Inputedges = [3,3,4,2,3]
Output3
Cycle 2 → 4 → 3 → 2 has length 3.

def longest_cycle(edges):
    n = len(edges)
    time = [0] * n
    ans, clock = -1, 1
    for start in range(n):
        if time[start]: continue
        cur, t0 = start, clock
        while cur != -1 and time[cur] == 0:
            time[cur] = clock
            clock += 1
            cur = edges[cur]
        if cur != -1 and time[cur] >= t0:
            ans = max(ans, clock - time[cur])
    return ans
function longestCycle(edges) {
  const n = edges.length;
  const time = new Array(n).fill(0);
  let ans = -1, clock = 1;
  for (let start = 0; start < n; start++) {
    if (time[start]) continue;
    let cur = start, t0 = clock;
    while (cur !== -1 && time[cur] === 0) {
      time[cur] = clock++;
      cur = edges[cur];
    }
    if (cur !== -1 && time[cur] >= t0) {
      ans = Math.max(ans, clock - time[cur]);
    }
  }
  return ans;
}
class Solution {
    public int longestCycle(int[] edges) {
        int n = edges.length;
        int[] time = new int[n];
        int ans = -1, clock = 1;
        for (int start = 0; start < n; start++) {
            if (time[start] != 0) continue;
            int cur = start, t0 = clock;
            while (cur != -1 && time[cur] == 0) {
                time[cur] = clock++;
                cur = edges[cur];
            }
            if (cur != -1 && time[cur] >= t0)
                ans = Math.max(ans, clock - time[cur]);
        }
        return ans;
    }
}
int longestCycle(vector<int>& edges) {
    int n = edges.size();
    vector<int> time(n, 0);
    int ans = -1, clock = 1;
    for (int start = 0; start < n; start++) {
        if (time[start]) continue;
        int cur = start, t0 = clock;
        while (cur != -1 && time[cur] == 0) {
            time[cur] = clock++;
            cur = edges[cur];
        }
        if (cur != -1 && time[cur] >= t0)
            ans = max(ans, clock - time[cur]);
    }
    return ans;
}
Time: O(n) Space: O(n)