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

Sum of Prefix Scores

trie · prefix counting

The score of a non-empty string p with respect to a word list is the number of words in the list that have p as a prefix (a word is a prefix of itself). For every word in words, return the sum of the scores of all its non-empty prefixes.

Examples

Input:  words = ["abc", "ab", "bc", "b"]
Output: [5, 4, 3, 2]
Explanation: for "abc": score("a") = 2, score("ab") = 2, score("abc") = 1, total 5.

Input:  words = ["abcd"]
Output: [4]

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…