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.
1function findSmallestSetOfVertices(n, edges) {
2 const hasIncoming = Array(n).fill(false);
3 edges.forEach(([_, to]) => {
4 hasIncoming[to] = true;
5 });
6 const result = [];
7 for (let i = 0; i < n; i++) {
8 if (!hasIncoming[i]) {
9 result.push(i);
10 }
11 }
12 return result;
13}
14
We create an array to keep track of incoming edges marking it true for nodes that are the destination of any edge. The nodes which remain unmarked are collected to form the result.