Chat app~50 min2s · 256 MBtarget O(n log² n + q) time, O(n log n) spacestring-algorithms · sorting
A support team stores a long chat export as one line of lowercase letters. Agents reuse the same phrases, so the line repeats itself often. The team wants to measure how far two points of the export repeat each other.
For two positions i and j, read forward from each position. The answer is how many letters match before the first difference, or before one of the two readings reaches the end of the line.
Write common_stretch(text, pairs).
text holds lowercase letters, and its positions start at 0.pairs[k] is [i, j]: two positions of text, which may be equal.text[i:] and text[j:] share at the start.Input: text = "mississippi", pairs = [[1,4],[0,3],[2,5],[4,7],[1,1],[3,6],[0,10],[5,8]]
Output: [4, 0, 3, 1, 10, 2, 0, 0]The readings from positions 1 and 4 are ississippi and issippi. They share issi, which is 4 letters. The readings from positions 1 and 1 are the same, so they share all 10 remaining letters.
The solution sorts all suffixes, then records for each suffix how many letters it shares with the one before it in the sorted order. Two suffixes share as many letters as the smallest of those numbers between them in the order.
| Place in the order | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Suffix start | 10 | 7 | 4 | 1 | 0 | 9 | 8 | 6 | 3 | 5 | 2 |
| Shared with the one before | 0 | 1 | 1 | 4 | 0 | 0 | 1 | 0 | 2 | 1 | 3 |
For the pair [1, 4], suffix 4 is at place 2 and suffix 1 is at place 3. The smallest number after place 2 up to place 3 is 4. For the pair [2, 5], the places are 10 and 9, and the smallest number after place 9 up to place 10 is 3.
Input: text = "z", pairs = [[0,0]]
Output: [1]A position matches itself for all the letters from it to the end.
Input: text = "aaaaa", pairs = [[0,1],[1,3],[0,4],[2,2]]
Output: [4, 2, 1, 3]The match is limited by the nearer end: from positions 1 and 3, only 2 letters remain after position 3.
1 ≤ text.length ≤ 100,000, and text has only the letters a to z1 ≤ pairs.length ≤ 100,000, and each pair is [i, j] with 0 ≤ i, j < text.lengthComparing two readings letter by letter can cost up to 100,000 steps, so 100,000 pairs on 100,000 equal letters cost about 5 × 10^9 steps. Sorting the suffixes once and building a table of minimums costs about 5 × 10^7 steps, and each pair costs two lookups.