TExcelTAD

Suffix Arrays: An Introduction

KMP and the automaton preprocess the pattern and then scan the text. When the text is fixed and many patterns will be searched in it (a genome, a code base, a book), it pays to preprocess the text instead. A suffix array lists the starting positions of all suffixes of the text in sorted order. Every occurrence of a pattern is a prefix of some suffix, and the suffixes starting with PP form one contiguous block of the sorted order, so a binary search finds them all in O(mlg⁡n)O(m \lg n) time. This lesson builds suffix arrays by prefix doubling, adds the LCP array of longest common prefixes, and uses both.

The definition

Let T[0..n−1]T[0..n-1] be the text. The suffix array SASA is the permutation of 0,…,n−10, \ldots, n - 1 such that

T[SA[0]..n−1]<T[SA[1]..n−1]<⋯<T[SA[n−1]..n−1]T[SA[0]..n-1] < T[SA[1]..n-1] < \cdots < T[SA[n-1]..n-1]

in lexicographic order (a proper prefix counts as smaller). It takes nn integers, much less than a suffix tree, which stores the same information as a compressed trie.

The obvious construction sorts the suffixes with string comparisons. A comparison may take Θ(n)\Theta(n) time, so this is O(n2lg⁡n)O(n^2 \lg n) in the worst case (for example, for ana^n), though fast on typical text.

python · try it yourself
T = "abaabab"
sa = sorted(range(len(T)), key=lambda i: T[i:])
print(" rank  SA  suffix")
for r, i in enumerate(sa):
    print(f"{r:5} {i:3}  {T[i:]}")
 rank  SA  suffix
    0   2  aabab
    1   5  ab
    2   0  abaabab
    3   3  abab
    4   6  b
    5   1  baabab
    6   4  bab

Prefix doubling

Prefix doubling (Manber and Myers, 1990) sorts the suffixes by their first kk characters for k=1,2,4,8,…k = 1, 2, 4, 8, \ldots, using the previous round's ranks. Let rk(i)r_k(i) be the rank of the suffix at ii among all suffixes when only their first kk characters count (equal prefixes get equal ranks). The first 2k2k characters of suffix ii are its first kk characters followed by the first kk characters of suffix i+ki + k, so

suffix i precedes suffix j in the 2k order  ⟺  (rk(i),rk(i+k))<(rk(j),rk(j+k)),\text{suffix } i \text{ precedes suffix } j \text{ in the } 2k \text{ order} \iff \bigl(r_k(i), r_k(i + k)\bigr) < \bigl(r_k(j), r_k(j + k)\bigr),

comparing pairs lexicographically, with rank −1-1 for positions past the end. Each round sorts pairs of integers, which a comparison sort does in O(nlg⁡n)O(n \lg n) and a radix sort in O(n)O(n). After at most ⌈lg⁡n⌉\lceil \lg n \rceil rounds all ranks are distinct, so the construction takes O(nlg⁡2n)O(n \lg^2 n) with comparison sorting or O(nlg⁡n)O(n \lg n) with radix sorting. (Linear-time constructions such as SA-IS exist, and are what libraries use.)

text
SUFFIX-ARRAY(T)
1  rank[i] = T[i] for every i; k = 1
2  repeat
3      sort the positions i by the pair (rank[i], rank[i + k])     // -1 past the end
4      give equal pairs equal new ranks, increasing along the sorted order
5      k = 2k
6  until all ranks are distinct
7  return the sorted positions
python · try it yourself
def suffix_array(T, verbose=False):
    n = len(T)
    rank = [ord(c) for c in T]
    sa, k = list(range(n)), 1
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)
        new = [0] * n
        for a, b in zip(sa, sa[1:]):
            new[b] = new[a] + (key(a) != key(b))
        rank = new
        if verbose:
            print(f"after sorting by {2 * k} characters: SA = {sa}, ranks = {rank}")
        if rank[sa[-1]] == n - 1:
            return sa
        k *= 2

T = "abaabab"
sa = suffix_array(T, verbose=True)
print("matches the naive sort:", sa == sorted(range(len(T)), key=lambda i: T[i:]))
after sorting by 2 characters: SA = [2, 0, 3, 5, 6, 1, 4], ranks = [1, 3, 0, 1, 3, 1, 2]
after sorting by 4 characters: SA = [2, 5, 0, 3, 6, 1, 4], ranks = [2, 5, 0, 3, 6, 1, 4]
matches the naive sort: True

The LCP array

The LCP array stores, for each pair of neighbours in the suffix array, the length of their longest common prefix: LCP[r]=lcp(T[SA[r−1]..],T[SA[r]..])LCP[r] = \mathrm{lcp}(T[SA[r-1]..], T[SA[r]..]) for r≥1r \ge 1. Kasai's algorithm (2001) computes it in O(n)O(n) time by visiting the suffixes in text order and using one fact: if the suffix at ii shares hh characters with its predecessor in the sorted order, then the suffix at i+1i + 1 shares at least h−1h - 1 with its own predecessor. So the current match length hh drops by at most 1 per step and increases at most 2n2n times in total, the same amortized argument as for KMP.

With SASA and LCPLCP many questions become easy:

  • Search. All suffixes beginning with PP form a block; two binary searches find its ends, each comparing PP with O(lg⁡n)O(\lg n) suffixes at O(m)O(m) cost: O(mlg⁡n)O(m \lg n) per pattern.
  • Distinct substrings. Every substring is a prefix of a suffix; suffix SA[r]SA[r] contributes n−SA[r]−LCP[r]n - SA[r] - LCP[r] new ones, so the count is ∑r(n−SA[r]−LCP[r])\sum_r (n - SA[r] - LCP[r]).
  • Longest repeated substring: the largest LCP value.
python · try it yourself
from bisect import bisect_left, bisect_right

def suffix_array(T):
    n, rank, sa, k = len(T), [ord(c) for c in T], list(range(len(T))), 1
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)
        new = [0] * n
        for a, b in zip(sa, sa[1:]):
            new[b] = new[a] + (key(a) != key(b))
        rank = new
        if rank[sa[-1]] == n - 1:
            return sa
        k *= 2

def kasai(T, sa):
    n = len(T)
    rank = [0] * n
    for r, i in enumerate(sa):
        rank[i] = r
    lcp, h = [0] * n, 0
    for i in range(n):                           # suffixes in text order
        if rank[i] > 0:
            j = sa[rank[i] - 1]
            while i + h < n and j + h < n and T[i + h] == T[j + h]:
                h += 1
            lcp[rank[i]] = h
            h = max(h - 1, 0)
        else:
            h = 0
    return lcp

def occurrences(T, sa, P):
    prefixes = [T[i:i + len(P)] for i in sa]     # for clarity; a real search compares in place
    lo, hi = bisect_left(prefixes, P), bisect_right(prefixes, P)
    return sorted(sa[lo:hi])

T = "abaabab"
sa = suffix_array(T)
lcp = kasai(T, sa)
for r, i in enumerate(sa):
    print(f"  SA[{r}] = {i}  LCP = {lcp[r]}  {T[i:]}")
print("occurrences of 'ab':", occurrences(T, sa, "ab"), " of 'aba':", occurrences(T, sa, "aba"))
distinct = sum(len(T) - i - l for i, l in zip(sa, lcp))
brute = len({T[a:b] for a in range(len(T)) for b in range(a + 1, len(T) + 1)})
print("distinct substrings:", distinct, " brute force:", brute)
r = max(range(len(T)), key=lambda r: lcp[r])
print("longest repeated substring:", T[sa[r]:sa[r] + lcp[r]])
  SA[0] = 2  LCP = 0  aabab
  SA[1] = 5  LCP = 1  ab
  SA[2] = 0  LCP = 2  abaabab
  SA[3] = 3  LCP = 3  abab
  SA[4] = 6  LCP = 0  b
  SA[5] = 1  LCP = 1  baabab
  SA[6] = 4  LCP = 2  bab
occurrences of 'ab': [0, 3, 5]  of 'aba': [0, 3]
distinct substrings: 19  brute force: 19
longest repeated substring: aba

The binary search above slices out prefixes for readability, which costs O(nm)O(nm); a real implementation compares PP with the suffix at the middle position directly, which keeps the search at O(mlg⁡n)O(m \lg n). With the LCP array the search can be sped up to O(m+lg⁡n)O(m + \lg n).

In C++

Prefix doubling with std::sort on rank pairs, then a binary search with std::lower_bound comparing the pattern directly against suffixes.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <initializer_list>
#include <string>
#include <utility>
#include <vector>

std::vector<int> suffix_array(const std::string& T) {
    int n = int(T.size());
    std::vector<int> sa(n), rank(n), tmp(n);
    for (int i = 0; i < n; i++) { sa[i] = i; rank[i] = (unsigned char)T[i]; }
    for (int k = 1;; k *= 2) {
        auto key = [&](int i) { return std::make_pair(rank[i], i + k < n ? rank[i + k] : -1); };
        std::sort(sa.begin(), sa.end(), [&](int a, int b) { return key(a) < key(b); });
        tmp[sa[0]] = 0;
        for (int r = 1; r < n; r++) tmp[sa[r]] = tmp[sa[r - 1]] + (key(sa[r - 1]) < key(sa[r]));
        rank = tmp;
        if (rank[sa[n - 1]] == n - 1) return sa;
    }
}

std::vector<int> occurrences(const std::string& T, const std::vector<int>& sa, const std::string& P) {
    auto less_than_p = [&](int i, const std::string& p) { return T.compare(i, p.size(), p) < 0; };
    auto p_less_than = [&](const std::string& p, int i) { return T.compare(i, p.size(), p) > 0; };
    auto lo = std::lower_bound(sa.begin(), sa.end(), P, less_than_p);
    auto hi = std::upper_bound(sa.begin(), sa.end(), P, p_less_than);
    std::vector<int> out(lo, hi);
    std::sort(out.begin(), out.end());
    return out;
}

int main() {
    std::string T = "she sells sea shells by the sea shore";
    auto sa = suffix_array(T);
    std::printf("first suffixes in order:");
    for (int r = 0; r < 4; r++) std::printf(" %d", sa[r]);
    std::printf("\n");
    for (std::string P : {"sea", "she", "s", "shell", "x"}) {
        std::printf("\"%s\":", P.c_str());
        for (int i : occurrences(T, sa, P)) std::printf(" %d", i);
        std::printf("\n");
    }
}
first suffixes in order: 20 9 27 3
"sea": 10 28
"she": 0 14
"s": 0 4 8 10 14 19 28 32
"shell": 14
"x":

T.compare(i, len, P) compares at most len characters of the suffix with PP, so a suffix that starts with PP compares equal, which makes the block of matches exactly the range between lower_bound and upper_bound. Suffix arrays and their compressed descendants (the FM-index, built on the Burrows-Wheeler transform) are the index structures behind DNA read aligners such as BWA and Bowtie; they come back in Advanced & Succinct Data Structures.

Test yourself

What is the suffix array of abab?

  1. 0 1 2 3
  2. 2 0 3 1
  3. 0 2 1 3
  4. 3 1 2 0

Why does prefix doubling need only O(lg⁡n)O(\lg n) rounds?

  1. Each round halves the text
  2. Each round doubles the number of characters by which the suffixes are sorted, and after nn characters all suffixes are distinct
  3. Because the alphabet is small
  4. Because of the LCP array

How long does it take to find all occurrences of a pattern of length mm with a suffix array of a text of length nn, by binary search?

  1. O(n+m)O(n + m)
  2. O(mlg⁡n)O(m \lg n) plus the number of occurrences
  3. O(nm)O(nm)
  4. O(lg⁡n)O(\lg n)

What does the largest value in the LCP array give?

  1. The number of distinct characters
  2. The length of the longest substring that occurs at least twice
  3. The longest palindrome
  4. The number of suffixes