Timestamped walks
Time O(n) Space O(n)Global clock. For each unvisited start, record startTime and walk, stamping nodes. If the walk stops at a node with stamp ≥ startTime, update the best with clock − stamp.
class Solution {
public int longestCycle(int[] edges) {
int n = edges.length, time = 1, best = -1;
int[] when = new int[n];
for (int i = 0; i < n; i++) {
if (when[i] != 0) continue;
int start = time, u = i;
while (u != -1 && when[u] == 0) { when[u] = time++; u = edges[u]; }
if (u != -1 && when[u] >= start) best = Math.max(best, time - when[u]);
}
return best;
}
}Verdict: Every node is stamped once.