Sum of Scores of Built Strings - Problem
Sum of Scores of Built Strings
Imagine you're building a string
Given the final string
•
•
• ... and so on
•
For example, if
•
•
•
•
•
The score of each
Goal: Return the sum of scores of all intermediate strings.
Imagine you're building a string
s character by character, but with a twist - each new character gets prepended to the front of the string! 🔄Given the final string
s of length n, we need to understand how it was built:•
s₁ = last character of s (added first)•
s₂ = last 2 characters of s (second character added)• ... and so on
•
sₙ = complete string sFor example, if
s = "abaca":•
s₁ = "a" (started with 'a')•
s₂ = "ca" (prepended 'c')•
s₃ = "aca" (prepended 'a')•
s₄ = "baca" (prepended 'b')•
s₅ = "abaca" (prepended 'a')The score of each
sᵢ is the length of the longest common prefix between sᵢ and the final string s.Goal: Return the sum of scores of all intermediate strings.
Input & Output
example_1.py — Basic Case
$
Input:
s = "babab"
›
Output:
9
💡 Note:
s₁="b" (score=1), s₂="ab" (score=0), s₃="bab" (score=3), s₄="abab" (score=0), s₅="babab" (score=5). Total: 1+0+3+0+5=9
example_2.py — All Same Characters
$
Input:
s = "aaaa"
›
Output:
10
💡 Note:
s₁="a" (score=1), s₂="aa" (score=2), s₃="aaa" (score=3), s₄="aaaa" (score=4). Total: 1+2+3+4=10
example_3.py — No Repeating Prefix
$
Input:
s = "abc"
›
Output:
3
💡 Note:
s₁="c" (score=0), s₂="bc" (score=0), s₃="abc" (score=3). Total: 0+0+3=3
Visualization
Tap to expand
Understanding the Visualization
1
Start with last character
Begin building from the rightmost character of final string
2
Prepend characters
Add each new character to the front, creating intermediate versions
3
Calculate scores
For each version, count how many characters from start match the final string
4
Sum all scores
Add up all the similarity scores to get the final answer
Key Takeaway
🎯 Key Insight: The problem reduces to computing the Z-array of the string, where each Z[i] represents the score of suffix starting at position i. The Z-algorithm solves this optimally in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
Z-algorithm processes each character at most twice using sliding window technique
✓ Linear Growth
Space Complexity
O(n)
Need to store the Z-array of size n
⚡ Linearithmic Space
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
- Time limit: 2 seconds
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code