Skip to content

Commit dfdfb81

Browse files
authored
Update 2416-sum-of-prefix-scores-of-strings.js
1 parent 6901a48 commit dfdfb81

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2416-sum-of-prefix-scores-of-strings.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {string[]} words
3+
* @return {number[]}
4+
*/
5+
const sumPrefixScores = (words) => {
6+
const n = words.length
7+
const trie = { _count: 0 }
8+
const result = []
9+
10+
// Create our own custom trie with _count property.
11+
// We are storing how many time we passed current node.
12+
for (let i = 0; i < n; i++) {
13+
const word = words[i]
14+
15+
let node = trie
16+
for (let j = 0; j < word.length; j++) {
17+
if (!node[word[j]]) node[word[j]] = {}
18+
node = node[word[j]]
19+
node._count = (node._count || 0) + 1
20+
}
21+
}
22+
23+
// Collect all _count values together as a result
24+
for (let i = 0; i < n; i++) {
25+
const word = words[i]
26+
let count = 0
27+
28+
let node = trie
29+
for (let j = 0; j < word.length; j++) {
30+
node = node[word[j]]
31+
count += node._count || 0
32+
}
33+
34+
result[i] = count
35+
}
36+
37+
return result
38+
}
39+
40+
// another
41+
142
/**
243
* @param {string[]} words
344
* @return {number[]}

0 commit comments

Comments
 (0)