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 with comparison sorting or with radix sorting, and prove the doubling invariant.
- Compute the LCP array with Kasai's algorithm in , 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 has suffixes, and every substring is a prefix of one of them: occurs at position exactly when the suffix starts with . Sort the suffixes and keep only where each one starts. That array, the suffix array (Manber & Myers, 1990), holds just integers, and the suffixes that start with a given form one contiguous block of it, which binary search finds.
| Suffix | |||
|---|---|---|---|
| 0 | 5 | a | 0 |
| 1 | 3 | ana | 1 |
| 2 | 1 | anana | 3 |
| 3 | 0 | banana | 0 |
| 4 | 4 | na | 0 |
| 5 | 2 | nana | 2 |
The obvious construction is a sort with whole suffixes as keys, sorted(range(n), key=lambda i: s[i:]) in Python. It makes comparisons that can each read characters, so time on a string like , and Python's slices also take 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 for the rank of among all such length- prefixes (equal prefixes get equal ranks, and a prefix cut short by the end of ranks as itself, so it sorts before its extensions). The key observation is that a prefix of length is a pair of prefixes of length : the one at and the one at .
Two strings of length compare like the pairs of their halves: the first halves decide, and on a tie the second halves do. With when (an empty second half sorts first):
So sorting the pairs and numbering the distinct ones in order gives . Starting from , the ranks of single characters, after rounds the order is correct on the first characters.
Once the prefixes are whole suffixes, which are all distinct, so the ranks form a permutation and is read off; often the ranks become distinct sooner, and the loop can stop there.
| Round | Sorted by | Ranks of positions 0…5 of banana |
|---|---|---|
| start | 1 character | (a = 0, b = 1, n = 2) |
| 2 characters | : ba, an, na, an, na, a | |
| 4 characters | : all distinct, so stop |
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 *= 2Each round sorts pairs, with a comparison sort, so in all. Ranks are below , so two stable passes of counting sort (second key, then first key: a radix sort) do a round in , for 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 , . With a sparse table for range minimum queries, that is per pair after preprocessing (see Sparse Tables & Square-Root Decomposition). Computing each by direct comparison costs up to each, in all on . Kasai's algorithm avoids that.
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 lcpnever exceeds and drops by at most 1 per position, so the inner loop's successful comparisons total at most : time. For banana it returns .
Why does Kasai's algorithm visit the suffixes in text order () rather than in sorted order?
- Because the suffix array is not available yet
- Because the guarantee "at least " links suffix to suffix , so the count carried over saves work only in text order
- Because sorted order would compute the same values, only more slowly by a constant factor
- Because text order visits the longest suffixes first
Show the answer
B. Because the guarantee "at least " links suffix to suffix , so the count carried over saves work only in text order
The lemma relates the LCP of suffix to that of suffix , neighbors in the text. Visiting them in that order lets 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 .
What the two arrays answer
| Question | Method | Cost after construction |
|---|---|---|
| Where does occur? | two binary searches for the block of suffixes that start with | ; with LCP information (Manber & Myers) |
| How many distinct substrings? | ||
| Longest substring occurring twice? | , read at | |
| Longest common substring of and ? | arrays of ; the largest whose two suffixes come from different strings | for |
| The -th smallest distinct substring? | walk ; suffix contributes new ones, in order |
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 has nonempty prefixes, and those of length at most are prefixes of the previous suffix too, so they were charged earlier.
No longer prefix of it was charged earlier: if a prefix of length 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 is a permutation:
For banana: . For a string of length the first term alone is , more than , so accumulate in a 64-bit integer.
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 characters, so a query costs , 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].
The string abab has and . How many distinct nonempty substrings does it have?
Show the answer
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 , with leaves and at most nodes, built in 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 ; every substring is a path from its start state. It has at most states and transitions and is built online, one character at a time, in amortized per character.
| Structure | Space | Construction | Strengths |
|---|---|---|---|
| suffix array + LCP | integers | by doubling, by SA-IS | compact, cache-friendly, simple; binary search and range-minimum tricks |
| suffix tree | nodes, with a constant several times that of the arrays | (Ukkonen, online) | pattern search, tree traversals for repeats and matching statistics |
| suffix automaton | states | online | appending characters, counting distinct substrings and occurrences on the fly |
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 -th, the longest repeat, or the longest common part of two or more strings. Sizes of to rule out the approaches.
| Problem | Key idea | Cost |
|---|---|---|
| Number of distinct substrings | with doubling | |
| Longest substring that occurs at least twice | maximum of the LCP array | |
| Longest common substring of two strings | arrays of ; neighbors from different sides | |
| Count occurrences of patterns that arrive online, in one fixed text | binary search for each pattern's block | per pattern |
| Lexicographically smallest rotation | the first suffix of that starts in the first half, cut to length |
A text of length is fixed. Then queries arrive one at a time, each answered before the next is revealed: "how many times does occur?", with . What fits?
- KMP for each query
- Aho–Corasick over all the queries
- A suffix array of the text, with two binary searches per query
- 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 or , and each query costs , about 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 characters using pairs of ranks: with comparison sorting, with radix sorting, in at most rounds.
- Kasai's algorithm computes the LCP array in by visiting suffixes in text order, because the LCP drops by at most 1 from suffix to suffix .
- Together the arrays answer pattern search (), distinct substrings (), longest repeats () and longest common substrings (via ).
- 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.
In the distinct-substring count, the suffix at row of the suffix array contributes new substrings. Why exactly fewer than its number of prefixes?
- Its first 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
- Because counts how often the suffix occurs in the text
- Because the last characters of the suffix repeat elsewhere
- Because suffixes shorter than are skipped
Show the answer
A. Its first 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 already seen are exactly those it shares with row , and there are of them.
To find the longest common substring of and , you index . What goes wrong if the separator also occurs inside ?
- Nothing: any character works as a separator
- The suffix array becomes impossible to build
- A common prefix of two suffixes can run through the separator, reporting a "common substring" that is not a substring of
- 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
With a unique separator, the common prefix of a suffix starting in and one starting in must stop before the , so it lies inside . If contains too, the match can continue through the separator into , and the reported string spans the boundary.
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?
- A suffix array, rebuilt after every append
- A suffix automaton, which adds new substrings per append
- An Aho–Corasick automaton of all prefixes
- A hash set of all substrings, updated after each append
Show the answer
B. A suffix automaton, which adds new substrings per append
The suffix automaton is built online in amortized 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.
What is the suffix array of "abab"?
Show the answer
C.
The suffixes are abab (0), bab (1), ab (2) and b (3). Sorted: ab < abab < b < bab, so . A proper prefix sorts before its extensions, which is why ab comes before abab.
Prefix doubling runs on a string of length whose ranks happen to stay tied as long as possible (such as ). About how many doubling rounds does it take?
- 20
- About 1,000
- 6
Show the answer
A. 20
After rounds the order is right on the first characters, and . So at most rounds, each a sort of pairs.
Go deeper
- Building Suffix Arrays: Doubling to SA-IS · Prefix doubling, Kasai’s LCP algorithm and linear-time construction.
- Suffix Trees & Suffix Automata · Ukkonen’s algorithm, the suffix automaton, and what each one answers.
- The Burrows–Wheeler Transform & FM-Index · Compression and search in one structure, behind genome alignment.
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.