Minimum Number of Vertices to Reach All Nodes - Problem

Given a directed acyclic graph (DAG) with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.

Find the smallest set of vertices from which all nodes in the graph are reachable. It is guaranteed that a unique solution exists.

Notice that you can return the vertices in any order.

Input & Output

Example 1 — Basic DAG
$ Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,3],[4,5]]
Output: [0,4]
💡 Note: From vertex 0, we can reach vertices 1, 2, and 3. From vertex 4, we can reach vertex 5. Vertices 0 and 4 have no incoming edges, so they must be in the minimum set.
Example 2 — Single Chain
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: [0]
💡 Note: This forms a chain 0→1→2. Starting from vertex 0, we can reach all vertices. Only vertex 0 has indegree 0.
Example 3 — No Edges
$ Input: n = 4, edges = []
Output: [0,1,2,3]
💡 Note: With no edges, all vertices are isolated. Each vertex can only reach itself, so all vertices must be in the minimum set.

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ edges.length ≤ min(105, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 ≤ fromi, toi < n
  • All pairs (fromi, toi) are distinct.
  • The input represents a valid DAG.

Visualization

Tap to expand
Minimum Vertices to Reach All Nodes012345In: 0In: 1In: 2In: 0In: 1Minimum Set: [0, 4]Vertices 0 and 4 have indegree 0, so they must be starting pointsFrom 0: can reach 1,2,3 | From 4: can reach 5
Understanding the Visualization
1
Input DAG
Directed acyclic graph with n=6 vertices and edges
2
Analyze Indegrees
Count incoming edges for each vertex
3
Minimum Set
Vertices with indegree 0 form the answer
Key Takeaway
🎯 Key Insight: Vertices with no incoming edges cannot be reached from other vertices, so they must be included in the minimum set
Asked in
Facebook 15 Google 12 Amazon 8
71.2K Views
Medium Frequency
~15 min Avg. Time
2.8K 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