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 Nodes INPUT Directed Acyclic Graph (DAG) 0 1 2 3 4 5 n = 6 edges = [[0,1],[0,2],[1,3], [2,3],[4,5]] ALGORITHM STEPS 1 Initialize Indegree Create array of size n 2 Count Indegrees For each edge, increment dest Indegree Count Node: 0 1 2 3 4 5 Indeg: 0 1 1 2 0 1 = 0 (source) 3 Find Zero Indegree Nodes with indegree = 0 4 Collect Results Return nodes 0 and 4 FINAL RESULT Minimum Vertex Set 0 SOURCE 4 SOURCE 1 2 3 5 Output: [0, 4] Key Insight: Nodes with ZERO indegree have NO incoming edges, meaning they CANNOT be reached from any other node. Therefore, they MUST be included in our starting set. These are the only nodes needed since all other nodes can be reached from them. Time: O(V+E) | Space: O(V) TutorialsPoint - Minimum Number of Vertices to Reach All Nodes | Indegree Analysis Approach
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