Skip to content

Commit b93298a

Browse files
authored
Create 2791-count-paths-that-can-form-a-palindrome-in-a-tree.js
1 parent 4c3700a commit b93298a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number[]} parent
3+
* @param {string} s
4+
* @return {number}
5+
*/
6+
const countPalindromePaths = function (parent, s) {
7+
let n = parent.length
8+
let dp = Array(n).fill(undefined)
9+
dp[0] = 0
10+
11+
function getDp(x) {
12+
if (dp[x] != undefined) return dp[x]
13+
dp[x] = getDp(parent[x]) ^ getMask(s[x])
14+
return dp[x]
15+
}
16+
17+
for (let i = 1; i < n; i++) getDp(i)
18+
dp.sort((a, b) => a - b)
19+
let counter = {}
20+
let res = 0
21+
22+
for (let i = 0; i <= n; i++) {
23+
if (counter[dp[i]]) counter[dp[i]]++
24+
else {
25+
counter[dp[i]] = 1
26+
27+
if (i) {
28+
let temp = dp[i - 1]
29+
let cntPrev = counter[temp]
30+
let c = 0
31+
32+
while (temp) {
33+
let b = temp & -temp
34+
c += counter[dp[i - 1] ^ b] ?? 0
35+
temp ^= b
36+
}
37+
38+
res += c * cntPrev + (cntPrev * (cntPrev - 1)) / 2
39+
}
40+
}
41+
}
42+
43+
return res
44+
}
45+
function getMask(c) {
46+
return 1 << (c.charCodeAt() - 97)
47+
}

0 commit comments

Comments
 (0)