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
Understanding the Visualization
1
Input
Array of words: ["abc", "ab", "bc", "b"]
2
Calculate
For each word, find score of each prefix
3
Output
Sum of prefix scores: [5, 4, 3, 2]
Key Takeaway
🎯 Key Insight: Use a trie to efficiently count how many words share each prefix
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code