You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si.

For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc.

The score of si is the length of the longest common prefix between si and sn (Note that s == sn).

Given the final string s, return the sum of the score of every si.

Input & Output

Example 1 — Basic Case
$ Input: s = "abaca"
Output: 7
💡 Note: s1="a" scores 1, s2="ca" scores 0, s3="aca" scores 1, s4="baca" scores 0, s5="abaca" scores 5. Total: 1+0+1+0+5=7
Example 2 — Single Character
$ Input: s = "a"
Output: 1
💡 Note: Only s1="a" which has 1 character matching with itself. Score: 1
Example 3 — All Different Characters
$ Input: s = "abc"
Output: 3
💡 Note: s1="c" scores 0, s2="bc" scores 0, s3="abc" scores 3. Total: 0+0+3=3

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Sum of Scores of Built Strings INPUT Final string s: a b a c a Built strings (prepending): s1 = "a" s2 = "ca" s3 = "aca" s4 = "baca" s5 = "abaca" n = 5 (length of string) s = "abaca" Input String ALGORITHM STEPS 1 Compare each suffix si with full string sn 2 Find LCP length Longest Common Prefix Suffix Comparisons with "abaca" s1="a" vs "abaca" LCP=1 s2="ca" vs "abaca" LCP=0 s3="aca" vs "abaca" LCP=1 s4="baca" vs "abaca" LCP=0 s5="abaca" vs "abaca" LCP=5 3 Sum all scores 1 + 0 + 1 + 0 + 5 = 7 FINAL RESULT Individual Scores: s1 1 s2 0 s3 1 s4 0 s5 5 Sum Calculation: 1 + 0 + 1 + 0 + 5 7 Total Score OK Key Insight: Each suffix si represents the string built at step i. The score measures how well each partial string matches the final string from the beginning. The full string sn always contributes its entire length (n) to the sum since it matches itself perfectly. TutorialsPoint - Sum of Scores of Built Strings | Direct Suffix Comparison Approach
Asked in
Google 12 Microsoft 8 Amazon 6
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen