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
DAG Ancestors - Reverse Graph DFS INPUT DAG with n=8 nodes 0 1 2 3 4 5 6 7 Edges Array: [0,3],[0,4],[1,3],[2,4], [2,7],[3,5],[3,6],[3,7],[4,6] n = 8 Nodes: 0 to 7 ALGORITHM STEPS 1 Build Reverse Graph Reverse all edge directions 2 DFS from Each Node Find all reachable nodes 3 Collect Ancestors Nodes reachable = ancestors 4 Sort Results Sort each list ascending Reverse Graph Example: 3 0 1 Original: 0-->3, 1-->3 Reversed: 3-->0, 3-->1 DFS from 3 finds ancestors 0,1 Time: O(n*(n+e)) | Space: O(n+e) FINAL RESULT Ancestors for each node: Node Ancestors 0 [ ] 1 [ ] 2 [ ] 3 [0, 1] 4 [0, 2] 5 [0, 1, 3] 6 [0, 1, 2, 3, 4] 7 [0, 1, 2, 3] OK Key Insight: By reversing the graph edges, finding ancestors becomes a reachability problem. A DFS from node v in the reversed graph reaches exactly those nodes that can reach v in the original graph (ancestors). This transforms "who can reach me?" into "who can I reach?" - a much simpler traversal problem. TutorialsPoint - All Ancestors of a Node in a Directed Acyclic Graph | Reverse Graph DFS Approach
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen