Suffix Trees and Suffix Arrays
String matching algorithms like KMP and Rabin-Karp preprocess the pattern and scan the text in 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 of length in time that depends on and the number of occurrences, but hardly on . 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 of length 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 is the compacted trie of all suffixes: each edge is labelled with a substring of (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 leaves and fewer than internal nodes, so nodes and words.
- It can be built in 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 . If the walk succeeds, the occurrences are the leaves below the point reached: 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 (Manber and Myers, 1990) lists the starting positions of the suffixes in lexicographic order: integers, bits, about 4 bytes per character. It keeps the main power of the suffix tree: all suffixes starting with are consecutive in , so two binary searches find the whole range of occurrences.
The LCP array stores , the length of the longest common prefix of the suffixes and . Together, and simulate a suffix tree: internal nodes correspond to intervals of with a common LCP value, and a bottom-up traversal of the suffix tree is a stack-based scan of (Abouelhoda, Kurtz and Ohlebusch, 2004).
Construction. The program builds by prefix doubling: after round the suffixes are sorted by their first characters, and the next round sorts by pairs of ranks (rank of the first half, rank of the second half), so rounds suffice. With a comparison sort that is ; with radix sort, . 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 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.
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 = 0def 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 = "mississippiquot;
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