Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Suffix Arrays & Suffix Trees

Index every suffix to answer substring questions fast.

How many distinct substrings does a string of 100,000 characters have? Up to about 5 billion, far too many to list. Yet one sorted array of 100,000 numbers, the suffix array, counts them in linear time once it is built, finds any pattern by binary search, and exposes the longest repeated substring.

What you’ll learn

  • Define the suffix array and the LCP array, and compute both for a small string by hand.
  • Build a suffix array by prefix doubling in O(nlog⁡2n)O(n \log^2 n) with comparison sorting or O(nlog⁡n)O(n \log n) with radix sorting, and prove the doubling invariant.
  • Compute the LCP array with Kasai's algorithm in O(n)O(n), and use both arrays for pattern search, distinct substrings, the longest repeated substring and the longest common substring.
  • Compare suffix arrays, suffix trees and suffix automata, and recognize problems that call for a suffix structure.

Sort the suffixes

A string of length nn has nn suffixes, and every substring is a prefix of one of them: pp occurs at position ii exactly when the suffix s[i..n−1]s[i..n-1] starts with pp. Sort the suffixes and keep only where each one starts. That array, the suffix array (Manber & Myers, 1990), holds just nn integers, and the suffixes that start with a given pp form one contiguous block of it, which binary search finds.

iisa[i]\mathrm{sa}[i]Suffixlcp[i]\mathrm{lcp}[i]
05a0
13ana1
21anana3
30banana0
44na0
52nana2
The suffix array of banana is [5,3,1,0,4,2][5, 3, 1, 0, 4, 2]. The two suffixes that start with "an", at rows 1 and 2, are adjacent: "an" occurs at positions 3 and 1.

The obvious construction is a sort with whole suffixes as keys, sorted(range(n), key=lambda i: s[i:]) in Python. It makes O(nlog⁡n)O(n \log n) comparisons that can each read Θ(n)\Theta(n) characters, so O(n2log⁡n)O(n^2 \log n) time on a string like ana^n, and Python's slices also take Θ(n2)\Theta(n^2) memory. That is fine for a few thousand characters; the rest of this lesson does better.

Prefix doubling

Prefix doubling sorts the suffixes by their first character, then by their first 2, 4, 8, … characters. Write rk(i)r_k(i) for the rank of s[i..i+k−1]s[i..i+k-1] among all such length-kk prefixes (equal prefixes get equal ranks, and a prefix cut short by the end of ss ranks as itself, so it sorts before its extensions). The key observation is that a prefix of length 2k2k is a pair of prefixes of length kk: the one at ii and the one at i+ki + k.

DerivationThe doubling invariant
  1. s[i..i+2k)<s[j..j+2k)  ⟺  (rk(i), rk(i+k))<(rk(j), rk(j+k))s[i..i+2k) < s[j..j+2k) \iff \big(r_k(i),\, r_k(i+k)\big) < \big(r_k(j),\, r_k(j+k)\big)

    Two strings of length 2k2k compare like the pairs of their halves: the first halves decide, and on a tie the second halves do. With rk(i+k)=−1r_k(i + k) = -1 when i+k≥ni + k \ge n (an empty second half sorts first):

  2. r1→r2→r4→⋯→r2tr_1 \to r_2 \to r_4 \to \cdots \to r_{2^t}

    So sorting the pairs and numbering the distinct ones in order gives r2kr_{2k}. Starting from r1r_1, the ranks of single characters, after tt rounds the order is correct on the first 2t2^t characters.

  3. t  ≤  ⌈log⁡2n⌉ roundst \;\le\; \lceil \log_2 n \rceil \ \text{rounds}

    Once 2t≥n2^t \ge n the prefixes are whole suffixes, which are all distinct, so the ranks form a permutation and sa\mathrm{sa} is read off; often the ranks become distinct sooner, and the loop can stop there.

RoundSorted byRanks of positions 0…5 of banana
start1 character[1,0,2,0,2,0][1, 0, 2, 0, 2, 0] (a = 0, b = 1, n = 2)
k=1k = 12 characters[2,1,3,1,3,0][2, 1, 3, 1, 3, 0]: ba, an, na, an, na, a
k=2k = 24 characters[3,2,5,1,4,0][3, 2, 5, 1, 4, 0]: all distinct, so stop
In the last round, position 3 gets the pair (1,0)(1, 0) (ana: "an", then "a") and position 1 the pair (1,1)(1, 1) (anan: "an", then "an"), so ana < anana. Listing positions by rank gives sa=[5,3,1,0,4,2]\mathrm{sa} = [5, 3, 1, 0, 4, 2].
python
def suffix_array(s):                     # prefix doubling with sorting: O(n log^2 n)
    n = len(s)
    rank = [ord(c) for c in s]           # round 0: rank by the first character
    sa = list(range(n))
    k = 1
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)                 # now sorted by the first 2k characters
        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 n == 0 or rank[sa[-1]] == n - 1:   # all ranks distinct: done
            return sa
        k *= 2

Each round sorts nn pairs, O(nlog⁡n)O(n \log n) with a comparison sort, so O(nlog⁡2n)O(n \log^2 n) in all. Ranks are below nn, so two stable passes of counting sort (second key, then first key: a radix sort) do a round in O(n)O(n), for O(nlog⁡n)O(n \log n) in all; the C++ contest version is in the Optimal lesson.

The LCP array in linear time

Neighbors in sorted order share the longest prefixes, and the LCP of any two suffixes is the minimum of the LCP array between them: for i<ji < j, LCP(s[sa[i]..], s[sa[j]..])=min⁡(lcp[i+1..j])\mathrm{LCP}(s[\mathrm{sa}[i]..],\ s[\mathrm{sa}[j]..]) = \min(\mathrm{lcp}[i+1..j]). With a sparse table for range minimum queries, that is O(1)O(1) per pair after O(nlog⁡n)O(n \log n) preprocessing (see Sparse Tables & Square-Root Decomposition). Computing each lcp[i]\mathrm{lcp}[i] by direct comparison costs up to Θ(n)\Theta(n) each, Θ(n2)\Theta(n^2) in all on ana^n. Kasai's algorithm avoids that.

python
def lcp_array(s, sa):                    # Kasai et al.: lcp[i] = LCP(sa[i-1], sa[i]), lcp[0] = 0
    n = len(s)
    rank = [0] * n
    for i, p in enumerate(sa):
        rank[p] = i
    lcp, h = [0] * n, 0
    for i in range(n):                   # suffixes in text order
        if rank[i] == 0:
            h = 0
            continue
        j = sa[rank[i] - 1]              # the suffix just before suffix i in sorted order
        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                       # suffix i + 1 keeps at least h - 1
    return lcp

hh never exceeds nn and drops by at most 1 per position, so the inner loop's successful comparisons total at most 2n2n: O(n)O(n) time. For banana it returns [0,1,3,0,0,2][0, 1, 3, 0, 0, 2].

Check your understanding

Why does Kasai's algorithm visit the suffixes in text order (i=0,1,2,…i = 0, 1, 2, \dots) rather than in sorted order?

  1. Because the suffix array is not available yet
  2. Because the guarantee "at least h−1h - 1" links suffix ii to suffix i+1i + 1, so the count carried over saves work only in text order
  3. Because sorted order would compute the same values, only more slowly by a constant factor
  4. Because text order visits the longest suffixes first
Show the answer

B. Because the guarantee "at least h−1h - 1" links suffix ii to suffix i+1i + 1, so the count carried over saves work only in text order

The lemma relates the LCP of suffix i+1i + 1 to that of suffix ii, neighbors in the text. Visiting them in that order lets hh start at the previous value minus one instead of zero; in sorted order consecutive suffixes have no such relation, and the work can grow to Θ(n2)\Theta(n^2).

What the two arrays answer

QuestionMethodCost after construction
Where does pp occur?two binary searches for the block of suffixes that start with ppO(mlog⁡n)O(m \log n); O(m+log⁡n)O(m + \log n) with LCP information (Manber & Myers)
How many distinct substrings?n(n+1)2−∑ilcp[i]\frac{n(n+1)}{2} - \sum_i \mathrm{lcp}[i]O(n)O(n)
Longest substring occurring twice?max⁡ilcp[i]\max_i \mathrm{lcp}[i], read at sa[i]\mathrm{sa}[i]O(n)O(n)
Longest common substring of ss and tt?arrays of s#ts\#t; the largest lcp[i]\mathrm{lcp}[i] whose two suffixes come from different stringsO(N)O(N) for N=∣s∣+∣t∣+1N = \abs{s} + \abs{t} + 1
The kk-th smallest distinct substring?walk sa\mathrm{sa}; suffix sa[i]\mathrm{sa}[i] contributes n−sa[i]−lcp[i]n - \mathrm{sa}[i] - \mathrm{lcp}[i] new ones, in orderO(n)O(n)
"Twice" allows overlaps: in banana the longest repeated substring is "ana", at positions 1 and 3, and in mississippi it is "issi", at 1 and 4. For the longest common substring, s=s = xabcdey and t=t = zbcdeabw give "bcde".
DerivationCounting distinct substrings
  1. new at row i  =  n−sa[i]−lcp[i]\text{new at row } i \;=\; n - \mathrm{sa}[i] - \mathrm{lcp}[i]

    Every distinct substring is a prefix of some suffix. Charge it to the first suffix, in sorted order, that has it as a prefix. The suffix at sa[i]\mathrm{sa}[i] has n−sa[i]n - \mathrm{sa}[i] nonempty prefixes, and those of length at most lcp[i]\mathrm{lcp}[i] are prefixes of the previous suffix too, so they were charged earlier.

  2. #distinct  =  ∑i=0n−1(n−sa[i]−lcp[i])  =  n(n+1)2−∑ilcp[i]\#\text{distinct} \;=\; \sum_{i=0}^{n-1} \big(n - \mathrm{sa}[i] - \mathrm{lcp}[i]\big) \;=\; \frac{n(n+1)}{2} - \sum_{i} \mathrm{lcp}[i]

    No longer prefix of it was charged earlier: if a prefix of length ℓ>lcp[i]\ell > \mathrm{lcp}[i] were a prefix of some earlier suffix, it would be a prefix of every suffix between them in sorted order, including the previous one. Summing over all rows, and using that sa\mathrm{sa} is a permutation:

  3. 6⋅72−6=15\tfrac{6 \cdot 7}{2} - 6 = 15

    For banana: 21−(1+3+0+0+2)=1521 - (1 + 3 + 0 + 0 + 2) = 15. For a string of length 10510^5 the first term alone is 5,000,050,0005{,}000{,}050{,}000, more than 231−12^{31} - 1, so accumulate in a 64-bit integer.

python
from bisect import bisect_left, bisect_right

def occurrences(s, sa, p):               # start positions of p, by two binary searches
    key = lambda i: s[i:i + len(p)]      # compare only the first |p| characters
    lo, hi = bisect_left(sa, p, key=key), bisect_right(sa, p, key=key)
    return sorted(sa[lo:hi])

Each probe compares at most ∣p∣\abs{p} characters, so a query costs O(∣p∣log⁡n)O(\abs{p} \log n), plus the output. The key argument of bisect needs Python 3.10 or later. occurrences("banana", [5, 3, 1, 0, 4, 2], "an") returns [1, 3].

Predict before you look

The string abab has sa=[2,0,3,1]\mathrm{sa} = [2, 0, 3, 1] and lcp=[0,2,0,1]\mathrm{lcp} = [0, 2, 0, 1]. How many distinct nonempty substrings does it have?

Show the answer

7

4⋅52−(2+0+1)=10−3=7\frac{4 \cdot 5}{2} - (2 + 0 + 1) = 10 - 3 = 7: a, b, ab, ba, aba, bab and abab. The 10 prefixes of suffixes include ab twice and b twice, which the LCP values subtract.

Suffix trees, suffix automata, and recognizing it

Two other structures index all suffixes:

  • The suffix tree is the compressed trie of all suffixes of s$s\$, with n+1n + 1 leaves and at most 2n+12n + 1 nodes, built in O(n)O(n) time for a constant alphabet (Weiner, 1973; McCreight, 1976; Ukkonen, 1995). Its leaves in alphabetical depth-first order spell the suffix array, and its internal nodes are the blocks of the suffix array whose LCP values stay at or above their depth, so the two arrays together can simulate it.
  • The suffix automaton is the smallest deterministic automaton accepting the suffixes of ss; every substring is a path from its start state. It has at most 2n−12n - 1 states and 3n−43n - 4 transitions and is built online, one character at a time, in amortized O(1)O(1) per character.
StructureSpaceConstructionStrengths
suffix array + LCP2n2n integersO(nlog⁡n)O(n \log n) by doubling, O(n)O(n) by SA-IScompact, cache-friendly, simple; binary search and range-minimum tricks
suffix treeO(n)O(n) nodes, with a constant several times that of the arraysO(n)O(n) (Ukkonen, online)O(m)O(m) pattern search, tree traversals for repeats and matching statistics
suffix automaton≤2n−1\le 2n - 1 statesO(n)O(n) onlineappending characters, counting distinct substrings and occurrences on the fly
Space per character for real suffix trees depends heavily on the implementation; the point is the constant factor, which is why suffix arrays and compressed indexes took over for large texts.

Recognizing it. Reach for a suffix structure when one fixed text faces many substring questions, or when a question ranges over all substrings: count the distinct ones, find the kk-th, the longest repeat, or the longest common part of two or more strings. Sizes of 10510^5 to 10610^6 rule out the O(n2)O(n^2) approaches.

ProblemKey ideaCost
Number of distinct substringsn(n+1)2−∑lcp\frac{n(n+1)}{2} - \sum \mathrm{lcp}O(nlog⁡n)O(n \log n) with doubling
Longest substring that occurs at least twicemaximum of the LCP arrayO(nlog⁡n)O(n \log n)
Longest common substring of two stringsarrays of s#ts\#t; neighbors from different sidesO(Nlog⁡N)O(N \log N)
Count occurrences of patterns that arrive online, in one fixed textbinary search for each pattern's blockO(mlog⁡n)O(m \log n) per pattern
Lexicographically smallest rotationthe first suffix of ssss that starts in the first half, cut to length nnO(nlog⁡n)O(n \log n)
"With doubling" refers to construction; SA-IS makes every row linear plus the query costs.
Check your understanding

A text of length 2×1052 \times 10^5 is fixed. Then 10510^5 queries arrive one at a time, each answered before the next is revealed: "how many times does pp occur?", with ∑∣p∣≤2×105\sum \abs{p} \le 2 \times 10^5. What fits?

  1. KMP for each query
  2. Aho–Corasick over all the queries
  3. A suffix array of the text, with two binary searches per query
  4. A hash set of all substrings of the text
Show the answer

C. A suffix array of the text, with two binary searches per query

The index is built once, in O(nlog⁡n)O(n \log n) or O(n)O(n), and each query costs O(∣p∣log⁡n)O(\abs{p} \log n), about 2×105×182 \times 10^5 \times 18 character comparisons in all. A suffix automaton with occurrence counts would also work.

Key takeaways

  • The suffix array lists the starting positions of the suffixes in sorted order; the suffixes beginning with a pattern form one block of it, and the LCP array records how much neighboring suffixes share.
  • Prefix doubling sorts by the first 2t2^t characters using pairs of ranks: O(nlog⁡2n)O(n \log^2 n) with comparison sorting, O(nlog⁡n)O(n \log n) with radix sorting, in at most ⌈log⁡2n⌉\lceil \log_2 n \rceil rounds.
  • Kasai's algorithm computes the LCP array in O(n)O(n) by visiting suffixes in text order, because the LCP drops by at most 1 from suffix ii to suffix i+1i + 1.
  • Together the arrays answer pattern search (O(mlog⁡n)O(m \log n)), distinct substrings (n(n+1)2−∑lcp\frac{n(n+1)}{2} - \sum \mathrm{lcp}), longest repeats (max⁡lcp\max \mathrm{lcp}) and longest common substrings (via s#ts\#t).
  • Recognize it by one fixed text with many substring queries, or questions over all substrings; suffix trees and automata answer the same questions, the automaton online.

Check yourself

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

Question 1

In the distinct-substring count, the suffix at row ii of the suffix array contributes n−sa[i]−lcp[i]n - \mathrm{sa}[i] - \mathrm{lcp}[i] new substrings. Why exactly lcp[i]\mathrm{lcp}[i] fewer than its number of prefixes?

  1. Its first lcp[i]\mathrm{lcp}[i] prefixes also start the previous suffix in sorted order, and any longer prefix shared with an earlier suffix would be shared with the previous one too
  2. Because lcp[i]\mathrm{lcp}[i] counts how often the suffix occurs in the text
  3. Because the last lcp[i]\mathrm{lcp}[i] characters of the suffix repeat elsewhere
  4. Because suffixes shorter than lcp[i]\mathrm{lcp}[i] are skipped
Show the answer

A. Its first lcp[i]\mathrm{lcp}[i] prefixes also start the previous suffix in sorted order, and any longer prefix shared with an earlier suffix would be shared with the previous one too

In sorted order, the set of suffixes that share a given prefix is a contiguous block. So the prefixes of row ii already seen are exactly those it shares with row i−1i - 1, and there are lcp[i]\mathrm{lcp}[i] of them.

Question 2

To find the longest common substring of ss and tt, you index s#ts\#t. What goes wrong if the separator #\# also occurs inside tt?

  1. Nothing: any character works as a separator
  2. The suffix array becomes impossible to build
  3. A common prefix of two suffixes can run through the separator, reporting a "common substring" that is not a substring of ss
  4. The LCP array becomes zero everywhere
Show the answer

C. A common prefix of two suffixes can run through the separator, reporting a "common substring" that is not a substring of ss

With a unique separator, the common prefix of a suffix starting in ss and one starting in tt must stop before the #\#, so it lies inside ss. If tt contains #\# too, the match can continue through the separator into tt, and the reported string spans the boundary.

Question 3

Characters are appended to a text one at a time, and after each append you must report how many distinct substrings the text has so far. Which structure handles this best?

  1. A suffix array, rebuilt after every append
  2. A suffix automaton, which adds len(last)−len(link(last))\mathrm{len}(\mathit{last}) - \mathrm{len}(\mathrm{link}(\mathit{last})) new substrings per append
  3. An Aho–Corasick automaton of all prefixes
  4. A hash set of all substrings, updated after each append
Show the answer

B. A suffix automaton, which adds len(last)−len(link(last))\mathrm{len}(\mathit{last}) - \mathrm{len}(\mathrm{link}(\mathit{last})) new substrings per append

The suffix automaton is built online in amortized O(1)O(1) per character, and the substrings that a new character creates are exactly the ones its new state adds, which gives the running count with no rebuilding. On banana the counts are 1, 3, 6, 9, 12, 15.

Question 4

What is the suffix array of "abab"?

  1. [0,2,1,3][0, 2, 1, 3]
  2. [3,1,2,0][3, 1, 2, 0]
  3. [2,0,3,1][2, 0, 3, 1]
  4. [2,0,1,3][2, 0, 1, 3]
Show the answer

C. [2,0,3,1][2, 0, 3, 1]

The suffixes are abab (0), bab (1), ab (2) and b (3). Sorted: ab < abab < b < bab, so sa=[2,0,3,1]\mathrm{sa} = [2, 0, 3, 1]. A proper prefix sorts before its extensions, which is why ab comes before abab.

Question 5

Prefix doubling runs on a string of length 10610^6 whose ranks happen to stay tied as long as possible (such as a106a^{10^6}). About how many doubling rounds does it take?

  1. 20
  2. About 1,000
  3. 10610^6
  4. 6
Show the answer

A. 20

After tt rounds the order is right on the first 2t2^t characters, and 220=1,048,576≥1062^{20} = 1{,}048{,}576 \ge 10^6. So at most ⌈log⁡2106⌉=20\lceil \log_2 10^6 \rceil = 20 rounds, each a sort of nn pairs.

Go deeper

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; first presented at SODA 1990.
  • 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).
  • D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997), part II.
  • CP-Algorithms, articles on suffix arrays and suffix automata, cp-algorithms.com.