All Ancestors of a Node in a Directed Acyclic Graph — LeetCode 2192 Python Solution
MediumDepth-First SearchBreadth-First SearchGraphTopological Sort
- Problem
- #2192
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
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
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(n^2).
- 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(n^2) 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.