Skip to content

Commit 27e5f2c

Browse files
committed
Added 2192
1 parent da1be64 commit 27e5f2c

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,7 @@
653653
| 2177 | [Count Equal and Divisible Pairs in an Array](src/2177.find-three-consecutive-integers-that-sum-to-a-given-number.py) | Medium | O(1) | O(1) | Math, Binary Search | | |
654654
| 2190 | [Most Frequent Number Following Key In an Array](src/2190.most-frequent-number-following-key-in-an-array.py) | Easy | O(N) | O(N) | Array, Hash Table, Counting | | |
655655
| 2191 | [Sort the Jumbled Numbers](src/2191.sort-the-jumbled-numbers.py) | Medium | O(NlogN) | O(1) | Array, Sorting | | |
656+
| 2192 | [All Ancestors of a Node in a Directed Acyclic Graph](src/2192.all-ancestors-of-a-node-in-a-directed-acyclic-graph.py) | Medium | O(N+V) | O(U+V) | DFS, BFS, Topological Sort, Graph | | |
656657

657658
## Useful Posts
658659

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#
2+
# @lc app=leetcode id=2192 lang=python3
3+
#
4+
# [2192] All Ancestors of a Node in a Directed Acyclic Graph
5+
#
6+
7+
# @lc code=start
8+
# TAGS: DFS, BFS, Topological Sort, Graph
9+
from typing import List
10+
import collections
11+
12+
13+
class Solution:
14+
# 800 mns, 90%. Time and Space: O(U+V)
15+
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
16+
memoization = {}
17+
18+
def dfs(node):
19+
if node in memoization:
20+
return memoization[node]
21+
22+
ancestor = {node}
23+
for nei in neis[node]:
24+
ancestor |= dfs(nei)
25+
memoization[node] = ancestor
26+
return ancestor
27+
28+
neis = collections.defaultdict(list)
29+
for u, v in edges:
30+
neis[v].append(u)
31+
32+
ans = [dfs(node) - {node} for node in range(n)]
33+
return [sorted(grp) for grp in ans]
34+
35+
# 1527 ms, 25.37%. Time and Space: O(N^2)
36+
def getAncestors2(self, n: int, edges: List[List[int]]) -> List[List[int]]:
37+
38+
def dfs(node, root):
39+
for nei in neis[node]:
40+
if ans[nei] and ans[nei][-1] == root:
41+
continue
42+
ans[nei].append(root)
43+
dfs(nei, root)
44+
45+
neis = collections.defaultdict(list)
46+
for u, v in edges:
47+
neis[u].append(v)
48+
49+
ans = [[] for _ in range(n)]
50+
for node in range(n):
51+
dfs(node, node)
52+
return ans
53+
# @lc code=end

0 commit comments

Comments
 (0)