Problem 460617 · medium · Level 04 Non-Linear Data Structures

How Crowded Is Every Word's Start?

trie · prefix counting

Within a word list, the score of a non-empty string p is how many words in the list begin with p (every word begins with itself). For each word in words, add up the scores of all its non-empty beginnings (its first letter, its first two letters, and so on up to the whole word) and return the totals in order.

Examples

Input:  words = ["car", "cat", "dog", "ca"]
Output: [7, 7, 3, 6]
Explanation: for "car": score("c") = 3, score("ca") = 3, score("car") = 1, total 7.

Input:  words = ["hello"]
Output: [5]

Constraints

  • 0 <= len(words) <= 10**4, lowercase non-empty words, total characters <= 10**5
  • Target: O(total characters)

Goals

  • Accumulate per-node counts during insertion
  • Read all counts along a word's path in a second pass
Starting Python…