Count Visited Nodes in a Directed Graph Problem
Description
LeetCode Problem 2876.
There is a directed graph consisting of n nodes numbered from 0 to n - 1 and n directed edges.
You are given a 0-indexed array edges where edges[i] indicates that there is an edge from node i to node edges[i].
Consider the following process on the graph:
- You start from a node
xand keep visiting other nodes through edges until you reach a node that you have already visited before on this same process.
Return an array answer where answer[i] is the number of different nodes that you will visit if you perform the process starting from node i.
Example 1:

Input: edges = [1,2,0,0]
Output: [3,3,3,4]
Explanation: We perform the process starting from each node in the following way:
- Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3.
- Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3.
- Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3.
- Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4.
Example 2:

Input: edges = [1,2,3,4,0]
Output: [5,5,5,5,5]
Explanation: Starting from any node we can visit every node in the graph in the process.
Constraints:
n == edges.length2 <= n <= 10^50 <= edges[i] <= n - 1edges[i] != i
Solution
Approach: Functional Graph Traversal
Every node has exactly one outgoing edge, so each walk ends in a cycle. Keep ans for the finished answers and vis for the step number at which the current walk reached each node.
For each node i without an answer, walk from i until reaching a node j that already has a step number. Two cases:
jwas reached in this walk: a new cycle was found. Its length iscnt - vis[j] + 1. Nodes on the cycle get that length, and each node before it gets the cycle length plus its distance to the cycle.jalready has an answer from an earlier walk: every node on this walk gets the distance tojplusans[j].
Walk the path a second time to write the answers. Each node is processed once.
Complexity: time O(n), space O(n), where n is the length of edges.
class Solution:
def countVisitedNodes(self, edges: List[int]) -> List[int]:
n = len(edges)
ans = [0] * n
vis = [0] * n
for i in range(n):
if not ans[i]:
cnt, j = 0, i
while not vis[j]:
cnt += 1
vis[j] = cnt
j = edges[j]
cycle, total = 0, cnt + ans[j]
if not ans[j]:
cycle = cnt - vis[j] + 1
total = cnt
j = i
while not ans[j]:
ans[j] = max(total, cycle)
total -= 1
j = edges[j]
return ans