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.
1def findSmallestSetOfVertices(n, edges):
2 has_incoming = [False] * n
3 for from_node, to_node in edges:
4 has_incoming[to_node] = True
5 result = [i for i in range(n) if not has_incoming[i]]
6 return result
7
We use a boolean list to determine nodes with incoming edges. We iterate through the edge list, updating nodes that have incoming edges. Finally, we return nodes that have no incoming edges.