You are given an array of strings. The "score" of a single string is defined as the sum of the number of strings in the array that start with each of its prefixes. For example, if the string is "abc", its prefixes are "a", "ab", and "abc". If there are 5 strings starting with "a", 3 starting with "ab", and 2 starting with "abc", the score for "abc" is 5 + 3 + 2 = 10. You need to return the total scores for all strings in the input.
Companies like Google, Amazon, and Bloomberg ask this Hard-level problem to test proficiency with Trie (Prefix Tree) data structures. It's a perfect application for Tries because Tries naturally group strings by their shared prefixes. A brute-force approach (comparing every string's prefixes against all other strings) would be O(N² * L²), which is incredibly slow. A Trie reduces this to O(N * L).
The pattern is "Trie with Prefix Counting."
count variable that increments every time a string passes through it.count stored at that node to the string's total score.Strings: ["abc", "ab"].
Tries are the "go-to" data structure for prefix-related problems. If you see "strings" and "prefixes" in a Hard problem, start by sketching out a Trie solution. Practice implementing a basic Trie from scratch, as many languages don't have one in their standard library.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Common Suffix Queries | Hard | Solve | |
| Words Within Two Edits of Dictionary | Medium | Solve | |
| Count the Number of Vowel Strings in Range | Easy | Solve | |
| Word Squares | Hard | Solve | |
| Palindrome Pairs | Hard | Solve |