Engineering platform~40 min2s · 256 MBtarget O(n) time, O(n) spacestring-algorithms · hashing
A platform team stores a long log line made of lowercase letters. The start of the line is a header, and parts of it come back later in the line. The team wants to know how often each start of the line repeats.
For each length k, take the first k letters of the line. Count the positions where those k letters appear anywhere in the line, including the start itself. Matches may overlap.
Write prefix_counts(text).
text holds lowercase letters, and its positions start at 0.k from 1 to text.length, count the positions i where text[i:i + k] equals text[:k]. Overlapping matches all count.text.length. Entry k - 1 is the count for length k.Input: text = "abcabcab"
Output: [3, 3, 2, 2, 2, 1, 1, 1]The first letter a appears at positions 0, 3 and 6. The start ab also appears at positions 0, 3 and 6. The start abc appears at positions 0 and 3, and so does abcab. The longer starts appear only at position 0.
The solution computes the Z function: z[i] is how many letters the text read from position i shares with the start of the text. The start of length k appears at position i exactly when z[i] ≥ k.
| Position i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Letter | a | b | c | a | b | c | a | b |
| z[i] | 8 | 0 | 0 | 5 | 0 | 0 | 2 | 0 |
The values 8, 5 and 2 each occur once, and 0 occurs five times. For length 5 the count is the number of z values at least 5, which is 2. For length 2 it is the number of z values at least 2, which is 3.
Input: text = "x"
Output: [1]A single letter appears once.
Input: text = "aaa"
Output: [3, 2, 1]The start a appears 3 times, aa appears at positions 0 and 1, and aaa appears once.
1 ≤ text.length ≤ 100,000text has only the letters a to zTesting every start against every position costs about n² / 2 comparisons, which is 5 × 10^9 for 100,000 letters, each of up to n letters. The Z function costs about 2n comparisons in total, and the counts cost two more passes.