Problem Description
Given a directed acyclic graph with n vertices labeled from 0 to n-1 and an array of directed edges, find the smallest set of vertices from which all nodes in the graph are reachable. It is guaranteed that a unique solution exists, and the vertices in the output can be in any order.
Key Insights
- In a graph, if a node does not have any incoming edge, it cannot be reached from any other node.
- Therefore, the minimal set of starting vertices must include all nodes with no incoming edges.
- By iterating over all edges once, we can mark which vertices have incoming edges.
- The final answer is simply the collection of vertices that were never targeted by any edge.
Space and Time Complexity
Time Complexity: O(n + m) where n is the number of vertices and m is the number of edges
Space Complexity: O(n) for tracking which vertices have incoming edges
Solution
The solution uses a simple array or list to track nodes that have incoming edges. The algorithm works as follows:
- Initialize an array of size n with all values set to false to indicate that initially no node is known to have an incoming edge.
- Iterate through each edge [u, v] and mark the target node v as having an incoming edge.
- After processing all edges, any node that is still marked false does not have any incoming edges and must be part of the minimal set.
- Return these nodes as the answer.
Data structures used: an array (or list) of booleans; algorithmic approach: single pass marking and collection.