Minimum Number of Vertices to Reach All Nodes (LeetCode 1557): Solution and Explanation

Medium
Graph

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

  1. Create has_incoming, a boolean per vertex, all false.
  2. For every edge [from, to], set has_incoming[to] = True.
  3. Scan the vertices in order and add each one whose flag is still false to the result.
  4. 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]]
  1. Read the edges and mark their targets: 1, 2, 5, 4, and 2 again.
  2. Marked vertices: 1, 2, 4, 5. Unmarked: 0 and 3.
  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.
  4. Check: from 0 we reach 1, 2 and 5; from 3 we reach 4, 2 and 5. Every vertex is covered.
  5. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

One pass over the m edges to mark targets and one pass over the n vertices to collect the unmarked ones.

Space

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.