#2223

Sum of Scores of Built Strings

Hard Z-algorithm

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The string is built by adding characters to the front one at a time. Each intermediate string's score is the length of the longest common prefix it shares with the final string. Return the sum of all scores.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for every suffix, how long a prefix of the full string does it start with? Add those up.

Why this works: that's exactly the Z-array, which the Z-algorithm builds in O(n) by reusing the furthest match window.

Example: "babab"

z = [5, 0, 3, 0, 1]sum = 9

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using int for the sum — it can reach about n²/2 and overflow.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon