Sum of Prefix Scores of Strings

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.

Example 1
Inputwords = ["abc","ab","bc","b"]
Output[5,4,3,2]
The prefix scores for "abc" are 2, 2, and 1; for "ab" are 2 and 2; for "bc" are 2 and 1; and for "b" is 2.
Example 2
Inputwords = ["abcd"]
Output[4]
"abcd" has 4 prefixes and each prefix has a score of one, so the total is 4.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] consists of lowercase English letters.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate