Problem Description
Given a directed graph represented by an array "edges" of size n, where each node i has an edge to edges[i], determine for every starting node the number of unique nodes visited before a node is revisited (i.e. when a cycle is encountered). In other words, simulate a process that follows the edges starting at each node until a previously seen node in that same process reoccurs, and report the count of distinct nodes visited.
Key Insights
- The graph is a functional graph where each node has exactly one outgoing edge.
- The structure is composed of cycles with trees feeding into them.
- When performing the process from any starting node, you eventually enter a cycle.
- Memoization can be used to store the answer for nodes that have been computed to avoid recomputation.
- Detect cycles by keeping track of the order of nodes encountered in the current processing chain.
Space and Time Complexity
Time Complexity: O(n) – Each node is processed at most once. Space Complexity: O(n) – Additional storage is used for memoization and tracking the current DFS/iteration chain.
Solution
The key is to notice that this is a functional graph where each node has exactly one outgoing edge. For each starting node, we simulate the process by following the chain of directed edges. We maintain a list (or stack) to record the order of nodes visited during the current exploration. A dictionary (or similar structure) maps each node to its index in the current chain; if we encounter a node already in this dictionary, a cycle is detected. The cycle length and the nodes leading into it can then be used to assign answers:
- Nodes in the cycle get a count equal to the length of the cycle.
- Nodes leading into the cycle get a count that is the distance from that node to the start of the cycle plus the cycle length.
- If we reach a node whose answer is already computed (memoized), we can use that to quickly calculate the result for the chain. This approach ensures that each node is visited at most once, achieving linear time complexity.