Problem Description
Given a directed acyclic graph (DAG) with n nodes numbered from 0 to n-1 and a list of directed edges, return for each node a sorted list (in ascending order) of all its ancestors. A node u is considered an ancestor of node v if there is a path from u to v.
Key Insights
- The problem is set in a DAG, ensuring the existence of a topological order.
- Propagation of ancestor information can be efficiently managed by processing nodes in topological order.
- For each node, the ancestors of its parent(s) along with the parent itself form the ancestors of the node.
- Using sets for each node avoids duplicate ancestors, and sorting each set in the end gives the required output order.
Space and Time Complexity
Time Complexity: O(n + m + (total union operations cost))
In the worst-case, each union operation may touch up to O(n) elements, leading to an overall bound that is pseudo-polynomial relative to the graph size.
Space Complexity: O(n^2) in the worst-case due to storing ancestors for each node.
Solution
We solve the problem by first computing the in-degrees for all nodes and using a queue to perform a topological sort. For every node processed, we update each of its children:
- Merge the current node’s ancestor set into the child’s ancestor set.
- Add the current node as a direct ancestor of the child. After processing all nodes, each node’s ancestor set is converted into a sorted list before returning. This approach leverages the properties of DAGs and ensures that ancestor information is propagated correctly and efficiently.