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 form one contiguous block of the sorted order, so a binary search finds them all in time. This lesson builds suffix arrays by prefix doubling, adds the LCP array of longest common prefixes, and uses both.
The definition
Let be the text. The suffix array is the permutation of such that
in lexicographic order (a proper prefix counts as smaller). It takes 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 time, so this is in the worst case (for example, for ), though fast on typical text.
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 characters for , using the previous round's ranks. Let be the rank of the suffix at among all suffixes when only their first characters count (equal prefixes get equal ranks). The first characters of suffix are its first characters followed by the first characters of suffix , so
comparing pairs lexicographically, with rank for positions past the end. Each round sorts pairs of integers, which a comparison sort does in and a radix sort in . After at most rounds all ranks are distinct, so the construction takes with comparison sorting or with radix sorting. (Linear-time constructions such as SA-IS exist, and are what libraries use.)
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 positionsdef 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: for . Kasai's algorithm (2001) computes it in time by visiting the suffixes in text order and using one fact: if the suffix at shares characters with its predecessor in the sorted order, then the suffix at shares at least with its own predecessor. So the current match length drops by at most 1 per step and increases at most times in total, the same amortized argument as for KMP.
With and many questions become easy:
- Search. All suffixes beginning with form a block; two binary searches find its ends, each comparing with suffixes at cost: per pattern.
- Distinct substrings. Every substring is a prefix of a suffix; suffix contributes new ones, so the count is .
- Longest repeated substring: the largest LCP value.
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 ; a real implementation compares with the suffix at the middle position directly, which keeps the search at . With the LCP array the search can be sped up to .
In C++
Prefix doubling with std::sort on rank pairs, then a binary search with std::lower_bound comparing the pattern directly against suffixes.
#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 , so a suffix that starts with 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?
- 0 1 2 3
- 2 0 3 1
- 0 2 1 3
- 3 1 2 0
Why does prefix doubling need only rounds?
- Each round halves the text
- Each round doubles the number of characters by which the suffixes are sorted, and after characters all suffixes are distinct
- Because the alphabet is small
- Because of the LCP array
How long does it take to find all occurrences of a pattern of length with a suffix array of a text of length , by binary search?
- plus the number of occurrences
What does the largest value in the LCP array give?
- The number of distinct characters
- The length of the longest substring that occurs at least twice
- The longest palindrome
- The number of suffixes