All Ancestors of a Node in a Directed Acyclic Graph LeetCode solution in JavaScript

1
var getAncestors = function (n, edges) {
2
const adj = [];
3
const ancestors = [];
4
const inDegrees = new Array(n).fill(0);
5

6
for (let i = 0; i < n; ++i) {
7
adj[i] = new Set();
8
ancestors[i] = new Set();
9
}
10

11
for (const [from, to] of edges) {
12
adj[from].add(to);
13
++inDegrees[to];
14
}
15

16
const queue = [];
17

18
for (let i = 0; i < n; ++i) {
19
if (inDegrees[i] === 0) queue.push(i);
20
}
21

22
while (queue.length > 0) {
23
const node = queue.shift();
24

25
for (const child of adj[node]) {
26
--inDegrees[child];
27

28
if (inDegrees[child] === 0) queue.push(child);
29

30
ancestors[child].add(node);
31
ancestors[node].forEach((prev) => ancestors[child].add(prev));
32
}
33
}
34

35
const res = [];
36

37
for (let i = 0; i < n; ++i) {
38
res[i] = [...ancestors[i]].sort((a, b) => a - b);
39
}
40

41
return res;
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0