Problem Description
Given a directed graph with n nodes (numbered from 0 to n-1) where each node has at most one outgoing edge (represented by the array edges), find the length of the longest cycle present in the graph. If there is no cycle in the graph, return -1.
Key Insights
- Each node can have at most one outgoing edge, which means the graph is composed of chains and possibly cycles.
- A cycle is detected when, during the traversal from a starting point, a node is revisited.
- Keeping track of the traversal path and the order in which nodes are visited allows us to compute the cycle’s length easily by subtracting the indices.
- Once a node has been fully processed (visited in any traversal), it can be skipped in future traversals to ensure linear time complexity.
- Using a dictionary (or map/array) to record the index of each node in the current path is essential to determine the cycle length when a revisited node is encountered.
Space and Time Complexity
Time Complexity: O(n) – Each node is visited at most once. Space Complexity: O(n) – For tracking visited nodes and indices in the current path.
Solution
We iterate over all nodes. For each unvisited node, we perform a traversal following its directed edge path. A map/dictionary is used to store the index (or step count) when a node is first encountered in the current traversal. If we meet a node that is already in the current mapping, then we have detected a cycle; the cycle's length is determined by subtracting the stored index from the current step index. After finishing a traversal from a node, mark all nodes in that path as visited so that they are not reprocessed. This method efficiently identifies cycles and calculates their lengths while ensuring that each node is processed only once.