TExcelTAD
Home › Advanced & Succinct Data Structures › Suffix Trees and Suffix Arrays

Suffix Trees and Suffix Arrays

String matching algorithms like KMP and Rabin-Karp preprocess the pattern and scan the text in O(n+m)O(n + m) time per query. When the text is fixed and queried many times (a genome, a document collection, a source tree), it pays to preprocess the text instead, into an index that finds all occurrences of a pattern PP of length mm in time that depends on mm and the number of occurrences, but hardly on nn. The two classic indexes are the suffix tree and the suffix array. The Part I course Selected Topics introduces suffix arrays; this lesson goes further, to their construction, the LCP array, their relation to suffix trees and their space.

Throughout, the text TT of length nn ends with a unique sentinel $\$ that is smaller than every other character, so that no suffix is a prefix of another.

Suffix trees

The suffix tree of TT is the compacted trie of all nn suffixes: each edge is labelled with a substring of TT (stored as a pair of positions), every internal node except the root has at least two children, and each leaf is labelled with the starting position of its suffix.

  • It has nn leaves and fewer than nn internal nodes, so O(n)O(n) nodes and O(n)O(n) words.
  • It can be built in O(n)O(n) time for a constant or integer alphabet: Weiner (1973), McCreight (1976), Ukkonen (1995, online, left to right), and Farach (1997) for integer alphabets.
  • Pattern search: walk down from the root along PP. If the walk succeeds, the occurrences are the leaves below the point reached: O(m+occ)O(m + \text{occ}) time with constant alphabet.
  • Many other problems become linear: the longest repeated substring (the deepest internal node), the longest common substring of two strings (a generalized suffix tree), counting distinct substrings, maximal repeats.

The drawback is space: a careful implementation needs about 10 to 20 bytes per text character, so a 3 GB genome needs tens of gigabytes.

Suffix arrays

The suffix array SASA (Manber and Myers, 1990) lists the starting positions of the suffixes in lexicographic order: nn integers, n⌈lg⁡n⌉n \lceil \lg n \rceil bits, about 4 bytes per character. It keeps the main power of the suffix tree: all suffixes starting with PP are consecutive in SASA, so two binary searches find the whole range of occurrences.

The LCP array stores LCP[j]LCP[j], the length of the longest common prefix of the suffixes SA[j−1]SA[j-1] and SA[j]SA[j]. Together, SASA and LCPLCP simulate a suffix tree: internal nodes correspond to intervals of SASA with a common LCP value, and a bottom-up traversal of the suffix tree is a stack-based scan of LCPLCP (Abouelhoda, Kurtz and Ohlebusch, 2004).

Construction. The program builds SASA by prefix doubling: after round kk the suffixes are sorted by their first 2k2^k characters, and the next round sorts by pairs of ranks (rank of the first half, rank of the second half), so ⌈lg⁡n⌉\lceil \lg n \rceil rounds suffice. With a comparison sort that is O(nlg⁡2n)O(n \lg^2 n); with radix sort, O(nlg⁡n)O(n \lg n). Linear-time algorithms exist: the skew algorithm DC3 (Kärkkäinen and Sanders, 2003) and SA-IS (Nong, Zhang and Chan, 2009), the latter being the practical favourite. The LCP array follows in O(n)O(n) with the algorithm of Kasai, Lee, Arimura, Arikawa and Park (2001), which processes suffixes in text order and uses the fact that the LCP of the next suffix drops by at most one.

text
KASAI-LCP(T, SA)
1  for j = 0 to n - 1:  RANK[SA[j]] = j
2  h = 0
3  for i = 0 to n - 1                       // suffixes in text order
4      if RANK[i] > 0
5          k = SA[RANK[i] - 1]               // the suffix before T[i..] in sorted order
6          while T[i + h] == T[k + h]:  h = h + 1
7          LCP[RANK[i]] = h
8          if h > 0:  h = h - 1              // T[i+1..] shares at least h - 1 with its predecessor
9      else  h = 0
python · try it yourself
def suffix_array(s):
    """Prefix doubling (Manber-Myers style): sort suffixes by their first 2^k characters, k = 0, 1, 2, ..."""
    n = len(s)
    rank = [ord(c) for c in s]
    sa = list(range(n))
    k, rounds = 1, 0
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)
        rounds += 1
        new = [0] * n
        for j in range(1, n):
            new[sa[j]] = new[sa[j - 1]] + (key(sa[j]) != key(sa[j - 1]))
        rank = new
        if rank[sa[-1]] == n - 1:                # all ranks distinct: done
            return sa, rounds
        k *= 2

def lcp_array(s, sa):
    """Kasai et al.: lcp[j] = longest common prefix of suffixes sa[j-1] and sa[j], in O(n) total."""
    n = len(s)
    rank = [0] * n
    for j, i in enumerate(sa): rank[i] = j
    lcp, h = [0] * n, 0
    for i in range(n):                           # suffixes in text order; h drops by at most 1 each step
        if rank[i] > 0:
            j = sa[rank[i] - 1]
            while i + h < n and j + h < n and s[i + h] == s[j + h]: h += 1
            lcp[rank[i]] = h
            if h: h -= 1
        else:
            h = 0
    return lcp

s = "mississippi
quot; sa, rounds = suffix_array(s) lcp = lcp_array(s, sa) print(f"text {s!r}: {rounds} doubling rounds") print(" j SA LCP suffix") for j, i in enumerate(sa): print(f"{j:2} {i:3} {lcp[j]:4} {s[i:]}") n = len(s) - 1 # without the sentinel print("distinct non-empty substrings:", n * (n + 1) // 2 - sum(lcp))
text 'mississippi
  

: 3 doubling rounds
 j  SA  LCP  suffix
 0  11    0  $
 1  10    0  i$
 2   7    1  ippi$
 3   4    1  issippi$
 4   1    4  ississippi$
 5   0    0  mississippi$
 6   9    0  pi$
 7   8    1  ppi$
 8   6    0  sippi$
 9   3    2  sissippi$
10   5    1  ssippi$
11   2    3  ssissippi$
distinct non-empty substrings: 53

The number of distinct substrings comes straight from the LCP array: every suffix contributes its length minus the part it shares with the previous suffix in sorted order, so the count is n(n+1)2−∑jLCP[j]\frac{n(n+1)}{2} - \sum_j LCP[j].

Searching

A pattern occurs at position ii exactly when PP is a prefix of the suffix T[i..]T[i..]. The suffixes with prefix PP form one interval of SASA, found by two binary searches, each comparing PP with O(lg⁡n)O(\lg n) suffixes at O(m)O(m) characters each: O(mlg⁡n+occ)O(m \lg n + \text{occ}) time. With the LCP information arranged for the binary search, Manber and Myers reduce this to O(m+lg⁡n+occ)O(m + \lg n + \text{occ}).

python · try it yourself
import random

def suffix_array(s):
    n = len(s)
    rank, sa, k = [ord(c) for c in s], 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 j in range(1, n):
            new[sa[j]] = new[sa[j - 1]] + (key(sa[j]) != key(sa[j - 1]))
        rank = new
        if rank[sa[-1]] == n - 1: return sa
        k *= 2

def find(s, sa, p):
    """All occurrences of p: two binary searches for the range of suffixes starting with p."""
    comps = 0
    def bound(strict):
        nonlocal comps
        lo, hi = 0, len(sa)
        while lo < hi:
            mid = (lo + hi) // 2
            comps += 1                            # one string comparison of up to |p| characters
            head = s[sa[mid]:sa[mid] + len(p)]
            if head < p or (strict and head == p): lo = mid + 1
            else: hi = mid
        return lo
    lo, hi = bound(False), bound(True)
    return sorted(sa[lo:hi]), comps

rng = random.Random(1990)
text = "".join(rng.choice("ACGT") for _ in range(20000)) + "
quot; sa = suffix_array(text) for p in ["GATTACA", "ACGT", "TTTTTT", "CAT"]: occ, comps = find(text, sa, p) naive = [i for i in range(len(text)) if text.startswith(p, i)] assert occ == naive print(f"{p:8}: {len(occ):4} occurrences, {comps} suffix comparisons (2 ceil(lg n) = {2 * (len(text) - 1).bit_length()})")
GATTACA :    3 occurrences, 29 suffix comparisons (2 ceil(lg n) = 30)
ACGT    :   90 occurrences, 29 suffix comparisons (2 ceil(lg n) = 30)
TTTTTT  :    5 occurrences, 28 suffix comparisons (2 ceil(lg n) = 30)
CAT     :  308 occurrences, 29 suffix comparisons (2 ceil(lg n) = 30)

About 2lg⁡n2 \lg n suffix comparisons per pattern, whatever the number of occurrences, and the occurrence list is a slice of SASA.

In C++

Prefix doubling with std::sort, Kasai's LCP algorithm and a search with std::lower_bound and std::upper_bound over std::string_view prefixes, on "abracadabra".

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <string>
#include <string_view>
#include <vector>

std::vector<int> suffix_array(const std::string& s) {        // prefix doubling with std::sort
    int n = static_cast<int>(s.size());
    std::vector<int> sa(n), rank(n), tmp(n);
    std::iota(sa.begin(), sa.end(), 0);
    for (int i = 0; i < n; ++i) rank[i] = static_cast<unsigned char>(s[i]);
    for (int k = 1;; k *= 2) {
        auto key = [&](int i) { return std::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 j = 1; j < n; ++j) tmp[sa[j]] = tmp[sa[j - 1]] + (key(sa[j - 1]) < key(sa[j]));
        rank = tmp;
        if (rank[sa[n - 1]] == n - 1) return sa;
    }
}

std::vector<int> lcp_array(const std::string& s, const std::vector<int>& sa) {   // Kasai et al.
    int n = static_cast<int>(s.size());
    std::vector<int> rank(n), lcp(n, 0);
    for (int j = 0; j < n; ++j) rank[sa[j]] = j;
    for (int i = 0, h = 0; i < n; ++i) {
        if (rank[i] == 0) { h = 0; continue; }
        int j = sa[rank[i] - 1];
        while (i + h < n && j + h < n && s[i + h] == s[j + h]) ++h;
        lcp[rank[i]] = h;
        if (h) --h;
    }
    return lcp;
}

int main() {
    std::string s = "abracadabra
quot;; auto sa = suffix_array(s); auto lcp = lcp_array(s, sa); for (std::size_t j = 0; j < sa.size(); ++j) std::printf("%2zu %3d %3d %s\n", j, sa[j], lcp[j], s.c_str() + sa[j]); long n = static_cast<long>(s.size()) - 1; long distinct = n * (n + 1) / 2 - std::accumulate(lcp.begin(), lcp.end(), 0L); std::printf("distinct non-empty substrings of abracadabra: %ld\n", distinct); std::string_view text(s), p("abra"); // range of suffixes starting with p auto lo = std::lower_bound(sa.begin(), sa.end(), p, [&](int i, std::string_view q) { return text.substr(i, q.size()) < q; }); auto hi = std::upper_bound(sa.begin(), sa.end(), p, [&](std::string_view q, int i) { return q < text.substr(i, q.size()); }); std::printf("\"abra\" occurs %td times, at", hi - lo); std::vector<int> pos(lo, hi); std::sort(pos.begin(), pos.end()); for (int i : pos) std::printf(" %d", i); std::printf("\n"); }
 0  11   0  $
 1  10   0  a$
 2   7   1  abra$
 3   0   4  abracadabra$
 4   3   1  acadabra$
 5   5   1  adabra$
 6   8   0  bra$
 7   1   3  bracadabra$
 8   4   0  cadabra$
 9   6   0  dabra$
10   9   0  ra$
11   2   2  racadabra$
distinct non-empty substrings of abracadabra: 54
"abra" occurs 2 times, at 0 7

Space and what comes next

Index Space (for nn characters) Search for PP
suffix tree O(n)O(n) words, about 10 to 20 bytes per character O(m+occ)O(m + \text{occ})
suffix array n⌈lg⁡n⌉n \lceil \lg n \rceil bits, 4 bytes per character for n<232n < 2^{32} O(mlg⁡n+occ)O(m \lg n + \text{occ}), or O(m+lg⁡n+occ)O(m + \lg n + \text{occ}) with LCP
suffix array + LCP about 2n2n words simulates suffix-tree algorithms
FM-index close to the text's entropy, often less than the text itself O(m)O(m) rank queries to count, plus O(lg⁡n)O(\lg n) per reported occurrence with sampling

The text itself needs only nlg⁡σn \lg \sigma bits for an alphabet of size σ\sigma (2 bits per character for DNA), so even a suffix array is 16 times larger than a DNA text. The next lesson compresses the index to about the size of the text, using the Burrows-Wheeler transform and rank queries.

Test yourself

Why are all occurrences of a pattern PP consecutive in the suffix array?

  1. Because the suffix array is a tree
  2. Because the suffixes that start with PP are exactly those between two lexicographic bounds, and the suffix array lists suffixes in lexicographic order
  3. Because of the sentinel
  4. Because patterns are short

How many distinct non-empty substrings does a string of length nn have, in terms of its LCP array?

  1. n2n^2
  2. n(n+1)2−∑jLCP[j]\frac{n(n+1)}{2} - \sum_j LCP[j]
  3. n−∑jLCP[j]n - \sum_j LCP[j]
  4. ∑jLCP[j]\sum_j LCP[j]

Why does Kasai's algorithm run in O(n)O(n) time?

  1. Because it sorts the suffixes
  2. Because moving from suffix ii to suffix i+1i + 1 decreases the current match length hh by at most 1, so hh increases at most 2n2n times in total
  3. Because the LCP values are small
  4. Because it uses a suffix tree