#2223

Sum of Scores of Built Strings

Hard
StringBinary SearchRolling HashSuffix ArrayString MatchingHash FunctionString MatchingZ-algorithmDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses the Z-algorithm to efficiently compute the longest common prefix lengths. The Z-array allows us to find the lengths of substrings that match the prefix of the string in linear time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Construct the Z-array for the string s.
  2. 2Step 2: Initialize a variable 'total_score' to 0.
  3. 3Step 3: Iterate through the Z-array, adding the values to 'total_score' where the index is less than the length of the string.
  4. 4Step 4: Return 'total_score' as the result.
solution.py21 lines
1# Full working Python code
2
3def z_algorithm(s):
4    z = [0] * len(s)
5    left, right, n = 0, 0, len(s)
6    for i in range(1, n):
7        if i <= right:
8            z[i] = min(right - i + 1, z[i - left])
9        while i + z[i] < n and s[z[i]] == s[i + z[i]]:
10            z[i] += 1
11        if i + z[i] - 1 > right:
12            left, right = i, i + z[i] - 1
13    return z
14
15def sum_of_scores(s):
16    z = z_algorithm(s)
17    total_score = sum(z) + len(s)
18    return total_score
19
20# Example usage
21print(sum_of_scores('babab'))  # Output: 9

Complexity note: The time complexity is O(n) because the Z-algorithm processes each character of the string a constant number of times, leading to linear growth in operations. The space complexity is O(n) due to the Z-array storage.

  • 1Understanding the relationship between prefixes and suffixes is crucial for this problem.
  • 2Using efficient algorithms like the Z-algorithm can drastically reduce computation time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.