Minimum Number of Vertices to Reach All Nodes (LeetCode 1557): Solution and Explanation
Given a directed acyclic graph, find the smallest set of starting vertices from which every vertex can be reached by following edges. The answer is unique and may be returned in any order.
Intuition
Start from the vertices that are forced. If no edge points into a vertex, the only way to reach it is to start there, so every vertex with in-degree 0 must be in the answer.
Now take any vertex that does have an incoming edge. Step backwards along one of its incoming edges, then again from that predecessor, and keep going. The graph has no cycles, so this backward walk cannot go on forever and must stop at a vertex with no incoming edge. That vertex is already in our set, and it reaches the vertex we started from.
So the in-degree 0 vertices are both necessary and enough. The problem never needs a search at all: one pass over the edges marks every target, and the unmarked vertices are the answer.
Approach: Collect the vertices with in-degree 0
- Create
has_incoming, a boolean per vertex, all false. - For every edge
[from, to], sethas_incoming[to] = True. - Scan the vertices in order and add each one whose flag is still false to the result.
- Return the result. Any order is accepted; scanning in index order gives ascending output.
Step-by-step example
n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
- Read the edges and mark their targets: 1, 2, 5, 4, and 2 again.
- Marked vertices: 1, 2, 4, 5. Unmarked: 0 and 3.
- Scan 0 to 5: 0 is unmarked, add it. 1 and 2 are marked. 3 is unmarked, add it. 4 and 5 are marked.
- Check: from 0 we reach 1, 2 and 5; from 3 we reach 4, 2 and 5. Every vertex is covered.
- Return [0, 3].
Code: Python, Java, C++
1class Solution:
2 def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
3 has_incoming = [False] * n
4 for frm, to in edges:
5 has_incoming[to] = True
6 result = []
7 for v in range(n):
8 if not has_incoming[v]:
9 result.append(v)
10 return result1class Solution {
2 public List<Integer> findSmallestSetOfVertices(int n, int[][] edges) {
3 boolean[] hasIncoming = new boolean[n];
4 for (int[] e : edges) {
5 hasIncoming[e[1]] = true;
6 }
7 List<Integer> result = new ArrayList<>();
8 for (int v = 0; v < n; v++) {
9 if (!hasIncoming[v]) {
10 result.add(v);
11 }
12 }
13 return result;
14 }
15}1class Solution {
2public:
3 vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
4 vector<bool> hasIncoming(n, false);
5 for (auto& e : edges) {
6 hasIncoming[e[1]] = true;
7 }
8 vector<int> result;
9 for (int v = 0; v < n; v++) {
10 if (!hasIncoming[v]) {
11 result.push_back(v);
12 }
13 }
14 return result;
15 }
16};Time and space complexity
O(n + m)
One pass over the m edges to mark targets and one pass over the n vertices to collect the unmarked ones.
O(n)
The boolean array has one entry per vertex; the result holds at most n vertices.
Other approaches
In-degree counts (time O(n + m), space O(n))
Count incoming edges per vertex instead of storing a flag, then return vertices with count 0. Same idea and cost, and the counts are reusable if you later need a topological sort.
Greedy DFS from every vertex (time O(n * (n + m)), space O(n + m))
Repeatedly start a DFS from an unvisited vertex and remove any earlier starts it reaches. It finds the same set but does far more work and is easy to get wrong.
Common mistakes
- Running BFS or DFS from every vertex when no search is needed; the structure of a DAG already proves the answer.
- Marking the source of each edge instead of the target. It is incoming edges that make a vertex unnecessary.
- Forgetting isolated vertices. A vertex with no edges at all has in-degree 0 and must be returned.
- Assuming this works for graphs with cycles. On a cycle every vertex has an incoming edge, so the in-degree rule alone would return nothing.
Frequently asked questions
Why are the in-degree 0 vertices enough?
From any vertex, walk backwards along incoming edges. Because the graph is acyclic, the walk must end at a vertex with no incoming edge, and that vertex reaches the one you started from.
Why are they all required?
Nothing points into an in-degree 0 vertex, so no other start can reach it. Leaving it out would leave it unreached.
Does the output order matter?
No. LeetCode accepts any order. Scanning vertices by index returns them in ascending order.
What is the time complexity?
O(n + m) time and O(n) space for n vertices and m edges.