#2416

Sum of Prefix Scores of Strings

Hard
ArrayStringTrieCountingTriePrefix TreeHash Map
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m)Space O(n * m)

Using a Trie allows us to efficiently count the occurrences of prefixes as we insert words. Each node in the Trie can keep track of how many words pass through it, making it easy to compute scores for each prefix.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a Trie data structure and insert all words into it, updating the count at each node.
  2. 2Step 2: For each word, traverse its prefixes in the Trie and sum the counts stored at each node.
  3. 3Step 3: Store the total score for each word in the result array.
solution.py31 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.count = 0
5
6class Trie:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def insert(self, word):
11        node = self.root
12        for char in word:
13            if char not in node.children:
14                node.children[char] = TrieNode()
15            node = node.children[char]
16            node.count += 1
17
18    def get_score(self, word):
19        node = self.root
20        score = 0
21        for char in word:
22            node = node.children[char]
23            score += node.count
24        return score
25
26
27def sumPrefixScores(words):
28    trie = Trie()
29    for word in words:
30        trie.insert(word)
31    return [trie.get_score(word) for word in words]

Complexity note: The time complexity is O(n * m) where n is the number of words and m is the average length of the words. The space complexity is O(n * m) due to the Trie storing all characters of the words.

  • 1Using a Trie allows efficient prefix counting as it organizes words hierarchically.
  • 2Each node in the Trie can maintain a count of how many words pass through it, making score calculation straightforward.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.