Minimum Number of Vertices to Reach All Nodes
Medium · Graphs · Explanation and code example
Indegree Count (Optimal)
How it works
We do not need to store the actual source vertices for each destination. We only care whether a vertex has at least one incoming edge. A simple boolean array is sufficient: mark each destination as having an incoming edge, then return all vertices that were never marked.
Steps
- Create a boolean array
indegreeof sizen, initialized tofalse. - For each edge
(src, dst), setindegree[dst] = true. - Collect all vertices
iwhereindegree[i]isfalse. - Return these vertices as
res.
Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)
Where
Vis the number of vertices andEis the number of edges.
Things to watch for
Tracking Outgoing Edges Instead of Incoming
The problem asks for nodes that cannot be reached from other nodes, which means nodes with zero incoming edges. Tracking outgoing edges instead will identify nodes that cannot reach others, which is the opposite of what is needed.
Overcomplicating With Graph Traversal
Since the graph is acyclic and we only need nodes with no incoming edges, a simple pass through the edges is sufficient. Implementing full DFS or BFS adds unnecessary complexity and potential for bugs when a simple indegree check solves the problem optimally.
Python code example
from typing import List
class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
indegree = [False] * n
for src, dst in edges:
indegree[dst] = True
return [i for i in range(n) if not indegree[i]]
C++ code example
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
vector<bool> indegree(n, false);
for (const auto& edge : edges) {
indegree[edge[1]] = true;
}
vector<int> res;
for (int i = 0; i < n; i++) {
if (!indegree[i]) {
res.push_back(i);
}
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.