The Count Visited Nodes in a Directed Graph interview question asks you to find the number of unique nodes reachable from each node in a graph where every node has exactly one outgoing edge. In such a graph, also known as a functional graph, the path starting from any node eventually enters a cycle. You need to return an array where each entry represents the total number of distinct nodes visited if you start a traversal from that specific node.
Companies like Google and Amazon use the Count Visited Nodes in a Directed Graph coding problem to evaluate a candidate's mastery of graph cycles and optimization techniques. Since the graph can have up to nodes, a naive traversal from each node would result in O(n^2) complexity, which is too slow. It tests your ability to use Memoization and identify the unique properties of functional graphs to achieve an O(n) solution.
This problem follows a Graph and Dynamic Programming pattern. The key is to identify the cycles within the graph.
Imagine a graph with nodes 0 to 4:
res[0]=3, res[1]=3, res[2]=3.
Starting from 3, you visit 3, then 0, 1, 2. Total unique nodes = 4. res[3] = 1 + res[0] = 4.
Starting from 4, you visit 4, 3, 0, 1, 2. Total unique nodes = 5. res[4] = 1 + res[3] = 5.Functional graphs always consist of a set of components, where each component has exactly one cycle. Recognizing this structure immediately simplifies many directed graph problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| The Earliest and Latest Rounds Where Players Compete | Hard | Solve | |
| Minimum Number of Days to Eat N Oranges | Hard | Solve | |
| The Most Similar Path in a Graph | Hard | Solve | |
| Number of Distinct Roll Sequences | Hard | Solve | |
| Cat and Mouse | Hard | Solve |