MediumNo. 2192
All Ancestors of a Node in a Directed Acyclic Graph — LeetCode 2192 Python Solution
- Pattern
- Topological Sort
- Topics
- Depth-First Search, Breadth-First Search, Graph, Topological Sort
- Reading time
- 4 min
- Source
- leetcode.com
The 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).
Example
- Input
- n = 8, edgeList = [[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,2,3,4],[0,1,2,3]]
- Explanation
- The above diagram represents the input graph.
Python solution
class Solution:
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
def bfs(s: int):
q = deque([s])
vis = {s}
while q:
i = q.popleft()
for j in g[i]:
if j not in vis:
vis.add(j)
q.append(j)
ans[j].append(s)
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
ans = [[] for _ in range(n)]
for i in range(n):
bfs(i)
return ansComplexity
- Time
- O(n2)
- Space · auxiliary
- O(n2)
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0207 | Course Schedule | Medium |
| 0210 | Course Schedule II | Medium |
| 0310 | Minimum Height Trees | Medium |
| 0802 | Find Eventual Safe States | Medium |
| 1203 | Sort Items by Groups Respecting Dependencies | Hard |
| 1462 | Course Schedule IV | Medium |
Frequently asked questions
- How hard is LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph?
LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph?
The Python solution on this page uses O(n2) auxiliary space.
- What topics does LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph cover?
LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph is tagged Depth-First Search, Breadth-First Search, Graph and Topological Sort on LeetCode.