Five string problems rated 2,000 to 2,200 on texts of 10^5 letters. The move: never compare two pieces of text from scratch twice; keep what the last comparison already proved.
This tent holds five problems rated 2,000 to 2,200, all on a text of up to 10^5 letters. One sorts every suffix, and one asks how far two suffixes agree. One counts distinct pieces. One counts how often each start repeats, and one matches thousands of words at once.
Comparing two pieces letter by letter is the first idea. A single comparison can cost 10^5 letters, and these problems need millions of them.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Every ending of a document, in order | sort the suffixes by comparing them | 1.7 × 10^11 letter comparisons |
| How far two points of a chat export repeat | compare the two suffixes for each pair | 10^10 letter comparisons |
| Distinct fragments of a reference code | collect every piece in a set | 5 × 10^9 pieces |
| How often each start of a log line repeats | match each start against the whole text | 10^10 comparisons |
| How often each banned word appears | search the text once per word | 10^10 comparisons |
All five reuse what a comparison already proved. The first example is the prefix function.
Exercise · Predict the output: The prefix function of abacaba. Entry i of the prefix function is the length of the longest proper prefix of the first i + 1 letters that is also their suffix. This computes it for the text abacaba. What does it print?
text = "abacaba"
pi = [0] * len(text)
for i in range(1, len(text)):
k = pi[i - 1]
while k > 0 and text[i] != text[k]:
k = pi[k - 1]
if text[i] == text[k]:
k += 1
pi[i] = k
print(*pi)Each comparison of two pieces of text tells you where they agree. A fast method keeps that and starts the next comparison after the matched part.
Never compare two pieces of text from scratch twice. Keep the matched prefix of the last comparison and start the next one from it.
The prefix function reuses the match when a letter fails: instead of starting over, it falls back to the next shorter prefix that is also a suffix. The sum of all fall-backs is at most n, so the whole text takes a linear pass.
The suffix array reuses ranks. After a round, every suffix has a rank by its first k letters. The next round sorts by the pair (rank of suffix i, rank of suffix i + k), which orders by the first 2k letters. After 17 rounds, k is above 10^5, and the suffixes are in order.
Aho-Corasick reuses matches across words. It builds a trie of all the words, and gives each node a failure link to the longest proper suffix that is also a node. One pass over the text then follows the trie and the links, and counts every match.
The prefix function never restarts a match: when a letter fails, it falls back to the next shorter border that is already known.
Exercise · Find the bug: The suffix that has nothing left. In the doubling step, every suffix is sorted by the pair (rank[i], second key). The second key is the rank of the suffix k places later. This returns the second key. Which line is wrong?
def second_key(rank, k, i):
return rank[i + k] if i + k < len(rank) else 0The Academy lessons String basics and Tries showed matching and a tree of words. Comparators taught sorting by a key, and Lower and upper bound taught binary search. This tent indexes the text itself, so that a question is a lookup.
The sorted suffixes make two questions cheap. The common prefix of two suffixes is the smallest value between them in the array of neighbour prefixes. The number of distinct substrings is n(n + 1)/2 minus the sum of those prefixes. Each suffix repeats exactly what it shares with its neighbour above.
The sum must run over neighbours in the sorted order. Neighbours in the text, suffix i and suffix i + 1, share nothing in general.
Distinct substrings subtract the common prefix of neighbours in the sorted order; neighbours in the text usually share nothing.
Exercise · Break it: The neighbours that are not sorted. This counts the different substrings of a text. It takes all n(n + 1)/2 pieces and subtracts the common prefix of each suffix with the next suffix in the text. Find an input where it is wrong.
def distinct_substrings(text):
n = len(text)
total = n * (n + 1) // 2
for i in range(n - 1):
k = 0
while i + 1 + k < n and text[i + k] == text[i + 1 + k]:
k += 1
total -= k
return total| Limit | What it tells you |
|---|---|
| a text of 10^5 letters | 17 rounds of doubling, each a sort of 10^5 pairs |
| distinct substrings of 10^5 letters | up to 5 × 10^9: 64-bit integers |
| 5,000 words of up to 20 letters | a trie of up to 10^5 nodes, and a table of 26 links per node |
| overlapping matches count | a word's count can be 10^5: add counts along failure links |
| letters a to z only | subtract 97 from each character code to index a table |
The full treatment is in Fast I/O and stress testing. A string problem reads one long line. The code below reads the text and prints how often each prefix occurs, from the prefix function.
import sys
def main():
text = sys.stdin.readline().strip()
n = len(text)
pi = [0] * n
for i in range(1, n):
k = pi[i - 1]
while k > 0 and text[i] != text[k]:
k = pi[k - 1]
if text[i] == text[k]:
k += 1
pi[i] = k
cnt = [0] * (n + 1)
for v in pi:
cnt[v] += 1
for i in range(n, 0, -1):
cnt[pi[i - 1]] += cnt[i]
sys.stdout.write(" ".join(str(cnt[i] + 1) for i in range(1, n + 1)) + "\n")
main()import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String text = in.readLine().trim();
int n = text.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k > 0 && text.charAt(i) != text.charAt(k)) k = pi[k - 1];
if (text.charAt(i) == text.charAt(k)) k++;
pi[i] = k;
}
long[] cnt = new long[n + 1];
for (int v : pi) cnt[v]++;
for (int i = n; i >= 1; i--) cnt[pi[i - 1]] += cnt[i];
StringBuilder out = new StringBuilder();
for (int i = 1; i <= n; i++) out.append(cnt[i] + 1).append(i < n ? " " : "\n");
System.out.print(out);
}
}#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string text;
cin >> text;
int n = text.size();
vector<int> pi(n, 0);
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k > 0 && text[i] != text[k]) k = pi[k - 1];
if (text[i] == text[k]) k++;
pi[i] = k;
}
vector<long long> cnt(n + 1, 0);
for (int v : pi) cnt[v]++;
for (int i = n; i >= 1; i--) cnt[pi[i - 1]] += cnt[i];
for (int i = 1; i <= n; i++) cout << cnt[i] + 1 << (i < n ? " " : "\n");
}const text = require("fs").readFileSync(0, "utf8").split("\n")[0].trim();
const n = text.length;
const pi = new Array(n).fill(0);
for (let i = 1; i < n; i++) {
let k = pi[i - 1];
while (k > 0 && text[i] !== text[k]) k = pi[k - 1];
if (text[i] === text[k]) k++;
pi[i] = k;
}
const cnt = new Array(n + 1).fill(0);
for (const v of pi) cnt[v]++;
for (let i = n; i >= 1; i--) cnt[pi[i - 1]] += cnt[i];
const out = [];
for (let i = 1; i <= n; i++) out.push(cnt[i] + 1);
process.stdout.write(out.join(" ") + "\n");On the sample abacaba, all four programs print 4 2 2 1 1 1 1: the prefix a occurs 4 times, ab and aba twice each, and the longer prefixes once.
The slow twin counts each prefix by comparing it with every position of the text. It cannot share a fall-back mistake with the fast code.
import random
from fast import prefix_counts
from slow import prefix_counts as slow_counts
for seed in range(1000):
rng = random.Random(seed)
text = "".join(rng.choice("ab") for _ in range(rng.randint(1, 12)))
if prefix_counts(text) != slow_counts(text):
print("different at", text)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. For the suffix array, give a missing second key the value 0 instead of -1, and seed 5 fails. For the text babaa it puts the suffix aa before a.
At 2,000 to 2,200 the structures are known, and the work is the detail: the sentinel, the order of the neighbours, the overlap. Write which comparison you reuse in one line before you code. Aim for about 50 minutes a problem, and keep 10 for the stress test on texts of up to 12 letters.
The two rated 2,000 build the two reusable tools: the suffix array by doubling, and the prefix function. The two rated 2,100 use the sorted order for common prefixes and distinct pieces. The last, rated 2,200, matches many words in one pass.
For each problem, write the comparison you reuse in one line. Then write the slow twin that compares from scratch, and stress test on texts of up to 12 letters.
Checkpoint · Strings, suffix structures
Q1/5 What does the prefix function of abacaba hold?
Answer: B
The entry at c is 0, and the following a, b, a extend the border a, ab, aba: 1, 2, 3.
Q2/5 What do all the structures in this tent have in common?
Answer: B
The prefix function falls back to a shorter border, the suffix array reuses ranks, and Aho-Corasick follows failure links.
Q3/5 In a doubling round, what second key does a suffix get when it has no letters at i + k?
Answer: B
Ranks start at 0, so 0 would tie with a real rank. For the text aa, a second key of 0 puts the suffix aa before a.
Q4/5 How many different substrings does abab have?
Answer: C
The pieces are a, b, ab, ba, aba, bab and abab. The count 10 is n(n + 1)/2 with nothing subtracted.
Q5/5 Which neighbours do you use when you subtract common prefixes to count distinct substrings?
Answer: B
In the text, suffixes i and i + 1 usually share nothing. In sorted order, neighbours share the repeated pieces. For abab the sorted neighbours ab and abab share 2.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.