Sum of Prefix Scores of Strings - Problem

Imagine you're working for a search engine optimization company and need to analyze how popular different word prefixes are across a collection of terms. Given an array of words, your task is to calculate prefix popularity scores.

The score of any string prefix is defined as the number of words in the array that have this prefix. For example, if we have ["apple", "app", "application", "cat"], then the prefix "app" has a score of 3 because it appears at the beginning of "apple", "app", and "application".

Your goal is to return an array where each element represents the sum of scores of all possible non-empty prefixes for the corresponding word. Remember, a word is considered a prefix of itself!

Example: For words = ["abc", "ab", "bc", "b"]
• Word "abc" has prefixes: "a" (score=1), "ab" (score=2), "abc" (score=1) → total = 4
• Word "ab" has prefixes: "a" (score=1), "ab" (score=2) → total = 3
• And so on...

Input & Output

example_1.py — Basic Example
$ Input: ["abc", "ab", "bc", "b"]
Output: [5, 4, 3, 2]
💡 Note: For "abc": prefixes are "a"(1), "ab"(2), "abc"(1) → 1+2+1=4. Wait, let me recalculate: "a" appears in "abc","ab" so score=2. "ab" appears in "abc","ab" so score=2. "abc" appears in "abc" so score=1. Total = 2+2+1=5.
example_2.py — Single Word
$ Input: ["programming"]
Output: [11]
💡 Note: Only one word, so each prefix of "programming" has score 1. Total = 1+1+1+...+1 = 11 (length of word).
example_3.py — All Different Prefixes
$ Input: ["a", "aa", "aaa"]
Output: [6, 5, 3]
💡 Note: For "a": prefix "a" appears in all 3 words, score = 3. For "aa": "a"(3) + "aa"(2) = 5. For "aaa": "a"(3) + "aa"(2) + "aaa"(1) = 6.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 1000
  • words[i] consists of lowercase English letters
  • Sum of all words[i].length ≤ 2 × 105

Visualization

Tap to expand
Search TermssearchseaseesoROOTs:3o:1e:3a:2e:1Prefix Popularity Scores"search": s(3) + e(3) + a(2) + ... = ?"sea": s(3) + e(3) + a(2) = 8"see": s(3) + e(3) + e(1) = 7"so": s(3) + o(1) = 4🔍 The tree structure makes prefix counting instant!
Understanding the Visualization
1
Build Index Tree
Create a tree structure where each path represents a prefix, and each node counts how many terms pass through it
2
Count Occurrences
As you add each search term, increment counters at each node along its path
3
Calculate Popularity
For any term, sum up all the counters along its path to get total prefix popularity
Key Takeaway
🎯 Key Insight: A Trie naturally maintains prefix counts at each node, making it the perfect data structure for prefix-related problems. No string comparisons needed!
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 25
43.7K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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