Count Visited Nodes in a Directed Graph - Problem

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 x and 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.

Input & Output

Example 1 — Basic Cycle
$ Input: edges = [2,0,3,2]
Output: [2,3,2,3]
💡 Note: Starting from node 0: 0→2→0 (visits 2 nodes). Starting from node 1: 1→0→2→0 (visits 3 nodes). Starting from node 2: 2→0→2 (visits 2 nodes). Starting from node 3: 3→2→0→2 (visits 3 nodes).
Example 2 — Self Loop
$ Input: edges = [1,2,2,4,4]
Output: [3,3,1,2,1]
💡 Note: Node 0: 0→1→2→2 (visits 3 nodes, stops at self-loop). Node 1: 1→2→2 (visits 2 nodes). Node 2: 2→2 (visits 1 node, immediate self-loop). Node 3: 3→4→4 (visits 2 nodes). Node 4: 4→4 (visits 1 node).
Example 3 — Linear Chain
$ Input: edges = [1,2,0]
Output: [3,3,3]
💡 Note: All nodes eventually cycle through 0→1→2→0, so each starting point visits all 3 nodes before repeating.

Constraints

  • n == edges.length
  • 2 ≤ n ≤ 105
  • 0 ≤ edges[i] ≤ n - 1
  • edges[i] != i

Visualization

Tap to expand
Count Visited Nodes: Walking in a Directed GraphInput: edges = [2,0,3,2]0123→2→0→0→2Walk examples:• Start 0: 0→2→0 (visits 2 nodes)• Start 1: 1→0→2→0 (visits 3 nodes)• Start 2: 2→0→2 (visits 2 nodes)• Start 3: 3→2→0→2 (visits 3 nodes)Output: [2,3,2,3]
Understanding the Visualization
1
Input Graph
Directed graph where each node points to exactly one other node
2
Walk Process
Follow edges until revisiting a node
3
Count Nodes
Return number of unique nodes visited from each start
Key Takeaway
🎯 Key Insight: Every path eventually hits a cycle - we can optimize by detecting cycles and reusing results
Asked in
Google 28 Microsoft 15 Amazon 12 Meta 8
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen