Search~50 min2s · 256 MBtarget O(n log² n) time, O(n) spacestring-algorithms · sorting
A text search index stores a document so that any phrase can be found with a binary search. For that, it needs every ending of the document, called a suffix, in alphabetical order. The suffix that starts at position i is the text from position i to the end.
The document is long and may repeat the same letters many times. Write the code that lists the suffixes in order.
Write suffix_order(text).
text holds lowercase letters, and its positions start at 0.text.length suffixes, from the smallest suffix to the largest.Input: text = "abracadabra"
Output: [10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2]The smallest suffix is a, which starts at position 10. Next come abra at position 7 and abracadabra at position 0. The largest is racadabra, at position 2.
The solution does not compare whole suffixes. It ranks all suffixes by their first letter, then by their first two letters, then four, then eight. Each round combines a suffix's rank with the rank of the suffix that starts width letters later. Rounds stop when every suffix has its own rank.
| Round | Width | Order of start positions after sorting | Distinct ranks |
|---|---|---|---|
| 1 | 1 | 10, 0, 7, 3, 5, 1, 8, 4, 6, 2, 9 | 8 |
| 2 | 2 | 10, 0, 7, 3, 5, 8, 1, 4, 6, 9, 2 | 10 |
| 3 | 4 | 10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2 | 11 |
After round 3 all eleven ranks differ, so the order is final. In round 3, suffixes 0 and 7 both begin with abra. Suffix 7 ends there, so it comes first.
Input: text = "q"
Output: [0]One suffix only.
Input: text = "aaaa"
Output: [3, 2, 1, 0]The suffixes are a, aa, aaa and aaaa. A shorter suffix that is a prefix of a longer one comes first.
1 ≤ text.length ≤ 100,000text has only the letters a to zSorting suffixes by comparing letter by letter can cost up to n letters per comparison. For 100,000 equal letters that is about 100,000 × 17 comparisons of up to 100,000 steps, more than 10^10 steps. Prefix doubling needs at most 17 rounds, each a sort of 100,000 keys.