Sponsored
Sponsored
The nodes that have no incoming edges cannot be reached by any other nodes. Thus, these nodes must be included in the result set for ensuring all nodes in the graph are reachable. This is because they can naturally be start points of paths that reach out to other nodes.
Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges.
Space Complexity: O(n) for storing incoming edges information.
1import java.util.ArrayList;
2import java.util.List;
3
4public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) {
5 boolean[] hasIncoming = new boolean[n];
6 for (List<Integer> edge : edges) {
7 hasIncoming[edge.get(1)] = true;
8 }
9 List<Integer> result = new ArrayList<>();
10 for (int i = 0; i < n; i++) {
11 if (!hasIncoming[i]) {
12 result.add(i);
13 }
14 }
15 return result;
16}
17
We maintain a boolean array to track nodes with incoming edges, iterate through the edge list to update it, then collect and return those nodes without any incoming edges.