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: Building "abaca"Building Process:s₁:aScore: 1s₂:caScore: 0s₃:acaScore: 1s₄:bacaScore: 0s₅:abacaScore: 5Final String (reference):abacaTotal Score: 1 + 0 + 1 + 0 + 5 = 7
Understanding the Visualization
1
Input
Final string s = "abaca"
2
Build Process
Prepend characters: a → ca → aca → baca → abaca
3
Score Calculation
Compare each intermediate string with final string
Key Takeaway
🎯 Key Insight: Each intermediate string is a suffix of the final string - use string matching algorithms like Z-algorithm for optimal performance
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