Skip to content

Commit ead9b6e

Browse files
authored
Create 2581-count-number-of-possible-root-nodes.js
1 parent df1e053 commit ead9b6e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[][]} edges
3+
* @param {number[][]} guesses
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
const rootCount = function (edges, guesses, k) {
8+
const lookup = new Set(guesses.map(([a, b]) => a * 1_000_000 + b))
9+
const adjList = edges.reduce(
10+
(adjList, [a, b]) => {
11+
adjList[a].push(b)
12+
adjList[b].push(a)
13+
return adjList
14+
},
15+
new Array(edges.length + 1).fill(0).map(() => []),
16+
)
17+
18+
const guessed = (a, b) => (lookup.has(a * 1_000_000 + b) ? 1 : 0)
19+
20+
const getCorrect = (node, parent) =>
21+
adjList[node].reduce(
22+
(total, child) =>
23+
child === parent
24+
? total
25+
: total + guessed(node, child) + getCorrect(child, node),
26+
0,
27+
)
28+
29+
const getTotal = (node, parent, correct) =>
30+
(correct >= k ? 1 : 0) +
31+
adjList[node].reduce(
32+
(total, child) =>
33+
child === parent
34+
? total
35+
: total +
36+
getTotal(
37+
child,
38+
node,
39+
correct - guessed(node, child) + guessed(child, node),
40+
),
41+
0,
42+
)
43+
44+
return getTotal(0, -1, getCorrect(0, -1))
45+
}

0 commit comments

Comments
 (0)