905. Prefix Match Scores
For a string s, the score of a starting position i is the length of the longest common prefix between s and the suffix of s that begins at i. Position 0 compares s with itself, so it always scores the full length of s.
Return the sum of the scores of all starting positions 0 to n-1, where n is the length of s. The sum can be large, so it is returned as a 64-bit integer.
Aim for time O(n) and O(n) extra space. Recomputing every score from scratch is O(n^2); a rolling hash with binary search per position gives O(n log n).
Example 1
- Input:
- s = "mangomango"
- Output:
- 15
- Explanation:
The suffix starting at index 5 matches the five letters 'mango' and index 0 scores 10, so the total is 10 + 5 = 15.
Example 2
- Input:
- s = "ququququ"
- Output:
- 20
- Explanation:
Suffixes starting at 0, 2, 4, 6 score 8, 6, 4, 2 and the odd starts score 0, so the total is 20.
Example 3
- Input:
- s = "velvet"
- Output:
- 8
- Explanation:
Position 0 scores 6 and position 3 (suffix 'vet') shares 've' with the start, so the total is 6 + 2 = 8.
Constraints
1 ≤ s.length ≤ 105
s contains only lowercase English letters.
The answer fits in a signed 64-bit integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)