Algo-Sim › String Algorithms
Sum of Scores of Built Strings (Z-function)
Hard · String Algorithms · step through it in Java, Python and C++ on your own input
The Z-function gives, for every i, how far s[i..] matches the start of s, in O(n): values inside the rightmost matched box are copied, and only new letters are compared.
Problem
Look at every suffix of s, including s itself. A suffix's score is the length of the longest prefix it shares with the whole of s. Return the sum of the scores of all suffixes.
Constraints
- 1 ≤ s.length ≤ 10⁵
- s contains only lowercase English letters
- The sum can exceed 2³¹ − 1, so use a 64-bit total
Edge cases to test
- One character
- All the same letter
- A pattern match at the very start
Follow-up questions
- How do you search a pattern with it?
- Compute Z on
pattern + "$" + text; every z value equal to the pattern length marks a match: O(n + m). - Why is it linear?
- The box [l, r) only moves right; inside it values are copied from earlier, and only expansion past r compares characters.
Solution
Java
public long sumScores(String s) {
int n = s.length();
int[] z = new int[n];
long total = n;
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i < r) z[i] = Math.min(r - i, z[i - l]);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;
if (i + z[i] > r) { l = i; r = i + z[i]; }
total += z[i];
}
return total;
}Python
def sum_scores(s):
n = len(s)
z = [0] * n
total = n
l = r = 0
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l])
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i + z[i]
total += z[i]
return totalC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
long long sumScores(string &s) {
int n = int(s.size());
vector<int> z = vector<int>(n);
long long total = n;
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i < r)
z[i] = std::min(r - i, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
z[i]++;
if (i + z[i] > r) {
l = i;
r = i + z[i];
}
total += z[i];
}
return total;
}
};