Sum of Prefix Scores of Strings - Problem

You are given an array words of size n consisting of non-empty strings.

We define the score of a string term as the number of strings words[i] such that term is a prefix of words[i].

For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc".

Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i].

Note that a string is considered as a prefix of itself.

Input & Output

Example 1 — Basic Case
$ Input: words = ["abc", "ab", "bc", "b"]
Output: [5, 4, 3, 2]
💡 Note: For "abc": "a" appears in 2 words ("abc", "ab") = 2, "ab" appears in 2 words = 2, "abc" appears in 1 word = 1. Total: 2+2+1=5
Example 2 — Single Characters
$ Input: words = ["a"]
Output: [1]
💡 Note: Only one word "a", so prefix "a" appears in 1 word, total score = 1
Example 3 — No Common Prefixes
$ Input: words = ["abc", "def", "ghi"]
Output: [3, 3, 3]
💡 Note: No words share prefixes, so each word's prefixes appear only in itself, giving scores 1+1+1=3 for each

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 1000
  • words[i] consists of lowercase English letters

Visualization

Tap to expand
Sum of Prefix Scores of Strings INPUT words array: "abc" "ab" "bc" "b" Build Trie Structure: root a:2 b:2 b:2 c:1 c:1 ALGORITHM STEPS 1 Build Trie Insert all words, track count at each node 2 Count Prefixes Each node stores how many words pass through 3 Query Each Word Traverse word's path, sum all node counts 4 Calculate Scores Sum = score of all prefixes of each word Score Calculation: "abc": a(2)+ab(2)+abc(1)=5 "ab": a(2)+ab(2)=4 "bc": b(2)+bc(1)=3 "b": b(2)=2 Result: [5, 4, 3, 2] FINAL RESULT Output Array: 5 4 3 2 [0] [1] [2] [3] abc ab bc b Score Breakdown: "abc" prefixes: a,ab,abc scores: 2+2+1 = 5 "ab" prefixes: a,ab scores: 2+2 = 4 "bc" prefixes: b,bc scores: 2+1 = 3 "b" prefixes: b scores: 2 = 2 OK - Answer: [5,4,3,2] Key Insight: Use a Trie with prefix counts: Store at each node how many words pass through it. For each word, traverse its path in the Trie and sum all node counts to get the total prefix score. Time: O(n * L) where L is average word length | Space: O(total characters in all words) TutorialsPoint - Sum of Prefix Scores of Strings | Optimal Trie Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen