Payments app~50 min2s · 256 MBtarget O(n log² n) time, O(n) spacestring-algorithms · sorting
A fraud team keeps a long reference string made of lowercase letters. They store every distinct piece of it, called a fragment, as a pattern to watch. A fragment is a run of consecutive letters, and the same fragment may appear at many places.
The team stores only fragments whose length is from low to high, both included. How many different fragments must it store?
Write distinct_fragments(text, low, high).
text holds lowercase letters.text. Two fragments are the same when they have the same letters, wherever they appear.low and at most high.Input: text = "banana", low = 2, high = 4
Output: 9The fragments of length 2 are ba, an, na: 3 different ones. Those of length 3 are ban, ana, nan, and ana appears twice, so there are 3 different ones. Those of length 4 are bana, anan, nana: 3 different ones. The total is 9.
The solution sorts all suffixes of the text, and records how many letters each shares with the one before it in the order. Go through the suffixes in order. A suffix of length L that shares h letters with its predecessor adds the fragments of lengths h + 1 to L, and no earlier suffix had them.
| Suffix | Start | Length L | Shared h | New lengths | Lengths between 2 and 4 |
|---|---|---|---|---|---|
| a | 5 | 1 | 0 | 1 | 0 |
| ana | 3 | 3 | 1 | 2 to 3 | 2 |
| anana | 1 | 5 | 3 | 4 to 5 | 1 |
| banana | 0 | 6 | 0 | 1 to 6 | 3 |
| nana | 4 | 4 | 0 | 1 to 4 | 3 |
| na | 2 | 2 | 2 | none | 0 |
The last column adds up to 0 + 2 + 1 + 3 + 3 + 0 = 9.
Input: text = "k", low = 1, high = 1
Output: 1One letter gives one fragment.
Input: text = "aaaa", low = 1, high = 4
Output: 4Each length gives one different fragment: a, aa, aaa and aaaa.
1 ≤ text.length ≤ 100,000, and text has only the letters a to z1 ≤ low ≤ high ≤ text.lengthCutting out every fragment of every length costs about n²/2 pieces. That is 5 × 10^9 for 100,000 letters, and each piece is long. Sorting the suffixes costs about 3 × 10^7 steps, and counting costs one more pass. The answer can reach 5 × 10^9, so it needs a 64-bit integer.