Imagine exploring a maze of one-way paths where each room has exactly one exit leading to another room. You're given a directed graph with n nodes numbered from 0 to n-1, where each node i has exactly one outgoing edge to node edges[i].
Your task is to simulate a traversal process starting from each node: keep following the edges until you revisit a node you've already seen in this journey. Count how many different nodes you visit during this process (including the starting node, but not counting the final revisited node).
Goal: Return an array where answer[i] represents the number of unique nodes visited when starting the traversal from node i.
Example: If you start at node 0 and follow the path 0→1→2→1, you visit nodes {0, 1, 2} before revisiting node 1, so the answer is 3.
Input & Output
Visualization
Time & Space Complexity
Each node is visited at most twice - once for cycle detection and once for result computation
We need space for recursion stack, memoization array, and cycle detection
Constraints
- n == edges.length
- 1 ≤ n ≤ 105
- 0 ≤ edges[i] ≤ n - 1
- edges[i] ≠ i for all i
- Each node has exactly one outgoing edge