You are given a Directed Acyclic Graph (DAG) with n vertices. Your goal is to find the smallest set of vertices from which all other nodes in the graph are reachable. You need to return the list of these vertices. Because it's a DAG, the solution is simpler than it might first appear in a general graph.
Companies like Microsoft and Airbnb ask this to test basic graph theory knowledge, specifically the concept of "in-degree." It's a "knowledge-check" problem—can the candidate recognize that in a DAG, any node that has no incoming edges must be included in the starting set, and any node that does have an incoming edge is reachable from somewhere else?
The algorithmic pattern is Graph Traversal (In-degree counting). In any DAG, a node is reachable from another node if there's a path. The "source" nodes (those with no incoming edges) are the only nodes that cannot be reached from any other node. Therefore, the minimum set of vertices to reach all nodes is simply the set of all nodes with an in-degree of zero.
Consider edges: [[0,1], [0,2], [2,5], [3,4], [4,2]].
[0, 3].
From 0, you reach 1, 2, 5. From 3, you reach 4 (and then 2, 5). Total coverage.The most common mistake is over-engineering the solution using Depth-First Search (DFS) or Breadth-First Search (BFS) for every node. While DFS/BFS can solve it, they are significantly slower and more complex than simply counting in-degrees. Another mistake is forgetting that the problem specifically mentions a Directed Acyclic Graph, which is why the in-degree logic works so cleanly.
Always check if a graph is a DAG. DAGs have unique properties (like the existence of source and sink nodes and topological sorting) that often allow for linear-time solutions to reachability and pathfinding problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Champion II | Medium | Solve | |
| Paths in Maze That Lead to Same Room | Medium | Solve | |
| Maximal Network Rank | Medium | Solve | |
| Find Center of Star Graph | Easy | Solve | |
| Shortest Path with Alternating Colors | Medium | Solve |