Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(nlog⁡n)O(n \log n) 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 T(n)=T(2n/3)+O(n)T(n) = T(2n/3) + O(n).
  • 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 O(n)O(n) time.

Prefix doubling in O(n log n)

Manber and Myers's prefix doubling sorts by the first kk characters, then 2k2k, using the rank pair (rk(i),rk(i+k))(r_k(i), r_k(i + k)). Ranks are integers below nn, 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 s$s\$: with a unique smallest sentinel, comparing cyclic shifts compares suffixes, and the second key of position ii is just position i+ki + k cyclically, so the order by second key comes for free from the previous round by shifting every position back by kk.

cpp
#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.

DerivationRounds and running time
  1. after round t: sorted by the first 2t characters\text{after round } t:\ \text{sorted by the first } 2^t \text{ characters}

    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:

  2. t  ≤  ⌈log⁡2(n+1)⌉t \;\le\; \lceil \log_2 (n + 1) \rceil

    The n+1n + 1 cyclic shifts of s$s\$ are all distinct (each has the sentinel at a different place), so all classes are distinct once 2t≥n+12^t \ge n + 1, and the loop stops at the latest then:

  3. T(n)=O(n)⋅⌈log⁡2(n+1)⌉=O(nlog⁡n)T(n) = O(n) \cdot \lceil \log_2 (n+1) \rceil = O(n \log n)

    Each round is two linear passes plus a counting sort over at most n+1n + 1 classes:

Kasai's algorithm, proved

DerivationProof
  1. h(i+1)  ≥  h(i)−1h(i + 1) \;\ge\; h(i) - 1

    Let rank\mathrm{rank} be the inverse of sa\mathrm{sa}. For a suffix ii that is not the smallest, let pred(i)=sa[rank[i]−1]\mathrm{pred}(i) = \mathrm{sa}[\mathrm{rank}[i] - 1] and h(i)=LCP(s[pred(i)..], s[i..])h(i) = \mathrm{LCP}(s[\mathrm{pred}(i)..],\, s[i..]). Lemma: if h(i)≥2h(i) \ge 2, then suffix i+1i + 1 is not the smallest suffix and the inequality below holds; if h(i)≤1h(i) \le 1 it holds trivially.

  2. rank[j+1]<rank[i+1],LCP(j+1, i+1)=h(i)−1\mathrm{rank}[j + 1] < \mathrm{rank}[i + 1], \qquad \mathrm{LCP}(j + 1,\, i + 1) = h(i) - 1

    Let j=pred(i)j = \mathrm{pred}(i). Since s[j]=s[i]s[j] = s[i] and suffix jj < suffix ii, deleting that common first character keeps the order: suffix j+1j + 1 < suffix i+1i + 1, and the two share h(i)−1≥1h(i) - 1 \ge 1 characters. Both are real suffixes, since h(i)≥2h(i) \ge 2 means suffix jj has at least two characters.

  3. h(i+1)=LCP(pred(i+1), i+1)  ≥  LCP(j+1, i+1)=h(i)−1h(i + 1) = \mathrm{LCP}(\mathrm{pred}(i+1),\, i+1) \;\ge\; \mathrm{LCP}(j+1,\, i+1) = h(i) - 1

    The predecessor of i+1i + 1 lies in sorted order between j+1j + 1 (inclusive) and i+1i + 1. In sorted order, the LCP of two suffixes is the minimum of the neighboring LCPs between them, so a suffix closer to i+1i + 1 shares at least as much with it:

  4. #comparisons  ≤  2n+n=O(n)\#\text{comparisons} \;\le\; 2n + n = O(n)

    Time. The algorithm keeps a counter h≤nh \le n 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 h≤1h \le 1, so the counter was already 0 after the usual decrement. Every successful character comparison raises hh by 1, so there are at most n+nn + n 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 Φ\Phi algorithm (2009) computes the same values in text order as the permuted LCP array, plcp[i]=h(i)\mathrm{plcp}[i] = h(i), with mostly sequential memory access, and converts to lcp\mathrm{lcp} at the end; the LCP array can also be induced during SA-IS itself.

Check your understanding

In the proof of Kasai's lemma, which fact guarantees that the predecessor of suffix i+1i + 1 shares at least h(i)−1h(i) - 1 characters with it?

  1. Suffix pred(i)+1\mathrm{pred}(i) + 1 sorts before suffix i+1i + 1 and shares h(i)−1h(i) - 1 characters with it, and the actual predecessor lies between them in sorted order
  2. The predecessor of i+1i + 1 is always pred(i)+1\mathrm{pred}(i) + 1
  3. Neighboring suffixes in text order always share a prefix
  4. The LCP array is non-increasing
Show the answer

A. Suffix pred(i)+1\mathrm{pred}(i) + 1 sorts before suffix i+1i + 1 and shares h(i)−1h(i) - 1 characters with it, and the actual predecessor lies between them in sorted order

The actual predecessor may differ from pred(i)+1\mathrm{pred}(i) + 1, but it sits between that suffix and i+1i + 1 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 {1,…,n}\{1, \dots, n\}, pads ss with zeros, and recurses on two thirds of the suffixes:

  1. Sample. Take the positions i mod 3≠0i \bmod 3 \ne 0. Radix-sort them by their triples s[i] s[i+1] s[i+2]s[i]\,s[i+1]\,s[i+2] and name each triple by its rank. If the names are not all distinct, form the string of names of the positions ≡1\equiv 1 followed by those ≡2(mod3)\equiv 2 \pmod 3; its suffixes correspond to the sampled suffixes, so sorting it recursively ranks every sampled suffix.
  2. The rest. Sort the positions i≡0(mod3)i \equiv 0 \pmod 3 by the pair (s[i],rank(i+1))(s[i], \mathrm{rank}(i + 1)) with one radix sort: i+1i + 1 is sampled, so its rank is known.
  3. Merge the two sorted lists, as in merge sort.
DerivationEach merge comparison is O(1), and the total is linear
  1. j≡1:(s[j], rank(j+1)) vs (s[i], rank(i+1))j \equiv 1:\quad \big(s[j],\ \mathrm{rank}(j+1)\big) \ \text{vs}\ \big(s[i],\ \mathrm{rank}(i+1)\big)

    Compare a sampled jj with an unsampled i≡0i \equiv 0. If j≡1j \equiv 1, then j+1≡2j + 1 \equiv 2 and i+1≡1i + 1 \equiv 1 are both sampled, so one character and one rank decide:

  2. j≡2:(s[j], s[j+1], rank(j+2)) vs (s[i], s[i+1], rank(i+2))j \equiv 2:\quad \big(s[j],\ s[j+1],\ \mathrm{rank}(j+2)\big) \ \text{vs}\ \big(s[i],\ s[i+1],\ \mathrm{rank}(i+2)\big)

    If j≡2j \equiv 2, then j+1≡0j + 1 \equiv 0 is not sampled, but j+2≡1j + 2 \equiv 1 and i+2≡2i + 2 \equiv 2 are, so two characters and one rank decide:

  3. T(n)=T ⁣(2n3)+O(n)  ⟹  T(n)≤cn(1+23+49+⋯ )=3cn=O(n)T(n) = T\!\left(\tfrac{2n}{3}\right) + O(n) \;\Longrightarrow\; T(n) \le cn\left(1 + \tfrac23 + \tfrac49 + \cdots\right) = 3cn = O(n)

    This works because {1,2}\{1, 2\} is a difference cover modulo 3: for any two residues, some shift by 0, 1 or 2 moves both into the sample. Recursion on ⌈2n/3⌉\lceil 2n/3 \rceil 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:

  1. Put the LMS suffixes at the ends of their buckets, in their sorted order.
  2. Scan the array left to right; whenever it holds a suffix pp with p−1p - 1 L-type, put p−1p - 1 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.
  3. Scan right to left, refilling each bucket from its end; whenever the array holds pp with p−1p - 1 S-type, put p−1p - 1 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.

StageSuffix array of banana$ (slots 0–6)
types of positions 0…6L 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 buckets6, –, 3, 1, –, –, –
L-type induced, left to right6, 5, 3, 1, 0, 4, 2
S-type induced, right to left6, 5, 3, 1, 0, 4, 2
The left-to-right scan meets 6 and places 5 (a, L) at the front of bucket a; meets 5 and places 4 (n) at the front of bucket n; meets 3 and places 2 in bucket n; meets 1 and places 0 in bucket b. The right-to-left scan re-places the S-type suffixes 1 and 3 at the end of bucket a. The preliminary round had already separated the LMS substrings $, ana$ and ana (from positions 6, 3 and 1), so no recursion was needed. Dropping the sentinel's 6 leaves [5,3,1,0,4,2][5, 3, 1, 0, 4, 2].
DerivationWhy SA-IS is linear
  1. #LMS  ≤  ⌊n/2⌋\#\mathrm{LMS} \;\le\; \lfloor n/2 \rfloor

    An LMS position ii has an L-type left neighbor, so i−1i - 1 is not LMS; and i+1i + 1 is not LMS because its left neighbor ii is S-type. Position 0 is never LMS. So for a string of length nn, sentinel included:

  2. T(n)≤T(n/2)+O(n)  ⟹  T(n)=O(n)T(n) \le T(n/2) + O(n) \;\Longrightarrow\; T(n) = O(n)

    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 O(n)O(n)). The recursion is on at most half the length:

Key takeaways

  • Prefix doubling with counting sort on cyclic shifts of s$s\$ builds the suffix array in O(nlog⁡n)O(n \log n) with at most ⌈log⁡2(n+1)⌉\lceil \log_2(n+1) \rceil rounds; it is the standard contest implementation.
  • Kasai's lemma, h(i+1)≥h(i)−1h(i+1) \ge h(i) - 1, makes LCP construction linear: process suffixes in text order and carry the counter.
  • DC3 sorts the two thirds of suffixes at positions ≢0(mod3)\not\equiv 0 \pmod 3 recursively, sorts the rest by one radix pass, and merges in O(1)O(1) per comparison thanks to a difference cover: T(n)=T(2n/3)+O(n)=O(n)T(n) = T(2n/3) + O(n) = O(n).
  • SA-IS classifies suffixes as L or S, sorts the at most n/2n/2 LMS suffixes recursively, and induces all others in two scans: T(n)=T(n/2)+O(n)=O(n)T(n) = T(n/2) + O(n) = O(n), and fast in practice.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

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?

  1. LSLSLLS
  2. SLSLSSL
  3. LSLSLSS
  4. 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.

Question 2

DC3 recursively sorts the suffixes at positions i mod 3≠0i \bmod 3 \ne 0. Why not just the even positions, which would make the recursion smaller?

  1. Because even positions are always LMS positions
  2. Because with modulus 3, any two positions ii and jj have an offset k≤2k \le 2 with i+ki + k and j+kj + k both sampled, so each merge comparison takes O(1)O(1); with even positions an even and an odd suffix can never be shifted onto two sampled positions together
  3. Because the recursion on half the positions would not terminate
  4. Because radix sorting needs triples
Show the answer

B. Because with modulus 3, any two positions ii and jj have an offset k≤2k \le 2 with i+ki + k and j+kj + k both sampled, so each merge comparison takes O(1)O(1); with even positions an even and an odd suffix can never be shifted onto two sampled positions together

The sample {1,2} mod 3\{1, 2\} \bmod 3 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.

Question 3

Why does SA-IS recurse on a string at most half as long as its input?

  1. Because exactly half of the positions are S-type
  2. Because no two LMS positions are adjacent and position 0 is never LMS, so there are at most ⌊n/2⌋\lfloor n/2 \rfloor of them
  3. Because the alphabet shrinks by half at each level
  4. 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 ⌊n/2⌋\lfloor n/2 \rfloor of them

An LMS position ii has an L-type left neighbor, so i−1i - 1 is not LMS, and i+1i + 1 cannot be LMS because its left neighbor ii is S-type. So T(n)≤T(n/2)+O(n)=O(n)T(n) \le T(n/2) + O(n) = O(n).

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).