Building Suffix Arrays: Doubling to SA-IS
Prefix doubling, Kasai’s LCP algorithm and linear-time construction.
For more than a decade after suffix arrays appeared in 1990, the only linear-time way to build one went through a suffix tree. In 2003 three groups independently found direct linear-time constructions, and in 2009 Nong, Zhang and Chan found SA-IS, which sorts at most half of the suffixes recursively and deduces the order of all the others in two linear scans. It is now the core of the fastest practical libraries.
What you’ll learn
- Implement prefix doubling in with counting sort on cyclic shifts, and bound its number of rounds.
- Prove Kasai's lemma and the linear running time of LCP construction.
- Explain the DC3 (skew) algorithm, why it samples two thirds of the positions, and solve .
- Classify suffixes as L- or S-type, find the LMS positions, run SA-IS's induced sorting on a small string, and prove that it takes time.
Prefix doubling in O(n log n)
Manber and Myers's prefix doubling sorts by the first characters, then , using the rank pair . Ranks are integers below , so each round is a radix sort of pairs: a stable counting sort by the second key, then one by the first. A common contest implementation appends a sentinel smaller than every character and sorts the cyclic shifts of : with a unique smallest sentinel, comparing cyclic shifts compares suffixes, and the second key of position is just position cyclically, so the order by second key comes for free from the previous round by shifting every position back by .
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
std::vector<int> suffix_array(const std::string& str) { // O(n log n)
std::string s = str + '\0'; // sentinel, smaller than every character
int n = s.size(), classes = 256;
std::vector<int> p(n), c(n), pn(n), cn(n), cnt(std::max(classes, n), 0);
for (char ch : s) cnt[(unsigned char)ch]++;
for (int i = 1; i < classes; i++) cnt[i] += cnt[i - 1];
for (int i = n - 1; i >= 0; i--) p[--cnt[(unsigned char)s[i]]] = i;
c[p[0]] = 0; classes = 1;
for (int i = 1; i < n; i++) {
if (s[p[i]] != s[p[i - 1]]) classes++;
c[p[i]] = classes - 1;
}
for (int k = 1; k < n && classes < n; k <<= 1) { // sorted by k chars -> by 2k
for (int i = 0; i < n; i++) pn[i] = (p[i] - k + n) % n; // already sorted by 2nd half
std::fill(cnt.begin(), cnt.begin() + classes, 0);
for (int i = 0; i < n; i++) cnt[c[pn[i]]]++;
for (int i = 1; i < classes; i++) cnt[i] += cnt[i - 1];
for (int i = n - 1; i >= 0; i--) p[--cnt[c[pn[i]]]] = pn[i]; // stable by 1st half
cn[p[0]] = 0; classes = 1;
for (int i = 1; i < n; i++) {
std::pair<int, int> cur = {c[p[i]], c[(p[i] + k) % n]};
std::pair<int, int> prev = {c[p[i - 1]], c[(p[i - 1] + k) % n]};
if (cur != prev) classes++;
cn[p[i]] = classes - 1;
}
c.swap(cn);
}
p.erase(p.begin()); // drop the sentinel's own suffix
return p;
}Tested against a naive sort on 20,000 random strings. The input must not contain the sentinel character '\0'; suffix_array("banana") returns 5 3 1 0 4 2.
Before the loop, positions are sorted and classed by one character. Each round doubles the sorted length while classes are still tied, by the pair argument of the Optimized lesson:
The cyclic shifts of are all distinct (each has the sentinel at a different place), so all classes are distinct once , and the loop stops at the latest then:
Each round is two linear passes plus a counting sort over at most classes:
Kasai's algorithm, proved
Let be the inverse of . For a suffix that is not the smallest, let and . Lemma: if , then suffix is not the smallest suffix and the inequality below holds; if it holds trivially.
Let . Since and suffix < suffix , deleting that common first character keeps the order: suffix < suffix , and the two share characters. Both are real suffixes, since means suffix has at least two characters.
The predecessor of lies in sorted order between (inclusive) and . In sorted order, the LCP of two suffixes is the minimum of the neighboring LCPs between them, so a suffix closer to shares at least as much with it:
Time. The algorithm keeps a counter that loses at most 1 per position. At the smallest suffix it restarts at 0, but nothing is lost there: by the lemma, the suffix just before it in the text had , so the counter was already 0 after the usual decrement. Every successful character comparison raises by 1, so there are at most of them, plus one failed comparison per position:
Kasai's loop jumps around the suffix array in random order, which is slow on large inputs because of cache misses. Kärkkäinen, Manzini and Puglisi's algorithm (2009) computes the same values in text order as the permuted LCP array, , with mostly sequential memory access, and converts to at the end; the LCP array can also be induced during SA-IS itself.
In the proof of Kasai's lemma, which fact guarantees that the predecessor of suffix shares at least characters with it?
- Suffix sorts before suffix and shares characters with it, and the actual predecessor lies between them in sorted order
- The predecessor of is always
- Neighboring suffixes in text order always share a prefix
- The LCP array is non-increasing
Show the answer
A. Suffix sorts before suffix and shares characters with it, and the actual predecessor lies between them in sorted order
The actual predecessor may differ from , but it sits between that suffix and in sorted order. Since the LCP over a sorted range is the minimum of the neighboring LCPs, being closer can only increase the common prefix.
Linear time I: the skew algorithm (DC3)
Kärkkäinen and Sanders's DC3 (2003) works over an integer alphabet , pads with zeros, and recurses on two thirds of the suffixes:
- Sample. Take the positions . Radix-sort them by their triples and name each triple by its rank. If the names are not all distinct, form the string of names of the positions followed by those ; its suffixes correspond to the sampled suffixes, so sorting it recursively ranks every sampled suffix.
- The rest. Sort the positions by the pair with one radix sort: is sampled, so its rank is known.
- Merge the two sorted lists, as in merge sort.
Compare a sampled with an unsampled . If , then and are both sampled, so one character and one rank decide:
If , then is not sampled, but and are, so two characters and one rank decide:
This works because is a difference cover modulo 3: for any two residues, some shift by 0, 1 or 2 moves both into the sample. Recursion on characters plus linear work per level sums to a geometric series:
Linear time II: induced sorting (SA-IS)
SA-IS (Nong, Zhang & Chan, 2009) needs only the LMS suffixes in the right order; everything else is induced:
- Put the LMS suffixes at the ends of their buckets, in their sorted order.
- Scan the array left to right; whenever it holds a suffix with L-type, put at the next free front slot of its bucket. An L-type suffix is larger than its successor, so the successor is always met first, and within a bucket the L-type suffixes come out in the order of their successors, which is their correct order.
- Scan right to left, refilling each bucket from its end; whenever the array holds with S-type, put at the next free end slot. This places every S-type suffix, LMS ones included, by the mirror argument.
The LMS order itself comes from one preliminary round of the same induction started from the LMS positions in any order: that sorts the LMS substrings (each running from one LMS position to the next). If their names are all distinct, the LMS suffixes are sorted; otherwise SA-IS recurses on the string of names.
| Stage | Suffix array of banana$ (slots 0–6) |
|---|---|
| types of positions 0…6 | L S L S L L S; LMS positions 1, 3, 6; buckets $: slot 0, a: 1–3, b: 4, n: 5–6 |
| LMS suffixes at the ends of their buckets | 6, –, 3, 1, –, –, – |
| L-type induced, left to right | 6, 5, 3, 1, 0, 4, 2 |
| S-type induced, right to left | 6, 5, 3, 1, 0, 4, 2 |
An LMS position has an L-type left neighbor, so is not LMS; and is not LMS because its left neighbor is S-type. Position 0 is never LMS. So for a string of length , sentinel included:
Typing, bucketing, the two induction rounds and the naming of LMS substrings are each a constant number of linear scans (the total length of all LMS substrings is ). The recursion is on at most half the length:
Key takeaways
- Prefix doubling with counting sort on cyclic shifts of builds the suffix array in with at most rounds; it is the standard contest implementation.
- Kasai's lemma, , makes LCP construction linear: process suffixes in text order and carry the counter.
- DC3 sorts the two thirds of suffixes at positions recursively, sorts the rest by one radix pass, and merges in per comparison thanks to a difference cover: .
- SA-IS classifies suffixes as L or S, sorts the at most LMS suffixes recursively, and induces all others in two scans: , and fast in practice.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Read the types of the positions of banana$ (S if the suffix there is smaller than the next suffix, L if larger; the sentinel is S). Which string is right, positions 0 to 6?
- LSLSLLS
- SLSLSSL
- LSLSLSS
- LLSLSLS
Show the answer
A. LSLSLLS
From the right: $ is S; a > $, so L; n > a, so L; a < n, so S; n > a, so L; a < n, so S; b > a, so L. Reading left to right: L S L S L L S. The LMS positions, S-type with an L-type left neighbor, are 1, 3 and 6.
DC3 recursively sorts the suffixes at positions . Why not just the even positions, which would make the recursion smaller?
- Because even positions are always LMS positions
- Because with modulus 3, any two positions and have an offset with and both sampled, so each merge comparison takes ; with even positions an even and an odd suffix can never be shifted onto two sampled positions together
- Because the recursion on half the positions would not terminate
- Because radix sorting needs triples
Show the answer
B. Because with modulus 3, any two positions and have an offset with and both sampled, so each merge comparison takes ; with even positions an even and an odd suffix can never be shifted onto two sampled positions together
The sample is a difference cover: for every residue pair some shift by 0, 1 or 2 lands both positions in the sample, where ranks are known. Even positions alone are no difference cover modulo 2: shifting an even and an odd position by the same amount never makes both even.
Why does SA-IS recurse on a string at most half as long as its input?
- Because exactly half of the positions are S-type
- Because no two LMS positions are adjacent and position 0 is never LMS, so there are at most of them
- Because the alphabet shrinks by half at each level
- Because induced sorting discards the L-type suffixes
Show the answer
B. Because no two LMS positions are adjacent and position 0 is never LMS, so there are at most of them
An LMS position has an L-type left neighbor, so is not LMS, and cannot be LMS because its left neighbor is S-type. So .
Further reading
- U. Manber & G. Myers, "Suffix arrays: a new method for on-line string searches," SIAM Journal on Computing 22(5) (1993), 935–948.
- T. Kasai, G. Lee, H. Arimura, S. Arikawa & K. Park, "Linear-time longest-common-prefix computation in suffix arrays and its applications," Proceedings of CPM (2001).
- J. Kärkkäinen, P. Sanders & S. Burkhardt, "Linear work suffix array construction," Journal of the ACM 53(6) (2006), 918–936; conference version by Kärkkäinen & Sanders, ICALP 2003.
- G. Nong, S. Zhang & W. H. Chan, "Two efficient algorithms for linear time suffix array construction," IEEE Transactions on Computers 60(10) (2011), 1471–1484; SA-IS first appeared at DCC 2009.
- S. J. Puglisi, W. F. Smyth & A. H. Turpin, "A taxonomy of suffix array construction algorithms," ACM Computing Surveys 39(2) (2007).