All Ancestors of a Node in a Directed Acyclic Graph - Problem
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph.
Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order.
A node u is an ancestor of another node v if u can reach v via a set of edges.
Input & Output
Example 1 — Basic DAG
$
Input:
n = 8, edges = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
›
Output:
[[],[],[],[0,1],[0,2],[0,1,3],[0,1,3,4],[0,1,2,3]]
💡 Note:
Node 3 has ancestors [0,1] because both 0→3 and 1→3. Node 7 has ancestors [0,1,2,3] because all can reach it through various paths.
Example 2 — Simple Chain
$
Input:
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
›
Output:
[[],[0],[0,1],[0,1,2],[0,1,2,3]]
💡 Note:
Linear chain: each node has all previous nodes as ancestors.
Example 3 — No Edges
$
Input:
n = 3, edges = []
›
Output:
[[],[],[]]
💡 Note:
No edges means no node can reach any other, so no ancestors exist.
Constraints
- 1 ≤ n ≤ 1000
- 0 ≤ edges.length ≤ min(2000, n × (n - 1) / 2)
- edges[i].length == 2
- 0 ≤ fromi, toi ≤ n - 1
- fromi ≠ toi
- There are no duplicate edges.
- The graph is acyclic.
Visualization
Tap to expand
Understanding the Visualization
1
Input DAG
Directed acyclic graph with nodes and edges
2
Find Paths
For each node, find all nodes that can reach it
3
Output Lists
Return sorted ancestor lists for each node
Key Takeaway
🎯 Key Insight: Build reverse graph and use DFS to efficiently find all ancestor relationships
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code