Suffix arrays, LCP and the FM-index
Construct suffix arrays and LCP, relate them to suffix trees, and search a Burrows-Wheeler transform using an FM-index.
After this lesson you can
- Construct a suffix array by prefix doubling and search patterns on it.
- Compute the LCP array with Kasai's algorithm and prove linear cost.
- Use suffix arrays and LCP for the longest repeated substring and the number of distinct substrings.
- Calculate and invert the BWT and explain why it helps compression.
- Implement backward search in an FM-index.
Before you start
Motivation: index the text, not the pattern
In the previous lesson, KMP, Rabin-Karp and Aho-Corasick preprocessed the pattern and then traversed the whole text in time per query. When text is huge and fixed and queries are numerous, the approach reverses: pay once to preprocess the text, then let each query cost something depending on , pattern length, and almost nothing on . Three real situations have exactly this shape:
- Align DNA reads. A sequencer produces hundreds of millions of short fragments (100 to 300 bases) that must be located in a reference genome of about bases. Traversing the genome for every read is unthinkable. Everyday aligners such as BWA (Li and Durbin, 2009) and Bowtie (Langmead and colleagues, 2009) index the genome with this lesson’s FM-index, fitting in a few gigabytes of RAM.
- Duplicates in a pretraining corpus. Lee and colleagues (2022) showed that removing repeated fragments of at least 50 tokens from LLM training corpora reduces verbatim memorization without degrading the model. Finding all long repeated substrings in hundreds of gigabytes of text is a suffix-array and LCP problem. The same index counts arbitrary-length -grams over trillion-token corpora, as the infini-gram engine does (Liu and colleagues, 2024).
- Search company code. A code search engine receives thousands of queries per minute over gigabytes of source. Tools such as livegrep answer each query on a suffix array of all code, and detecting copied code reduces to finding maxima in an integer array.
The observation making this possible is elementary: every substring of is a prefix of some suffix of . Thus “does occur in ?” is the same as “is a prefix of some suffix?”. Alphabetically sort the suffixes and all starting with are adjacent, so a binary search finds the block. The lesson’s central object is that order, stored as a permutation of : it occupies integers, not characters.
The lesson constructs that array (by prefix doubling, in ), adds the LCP array (Kasai, in ), solves classic repetition problems and relates it to the suffix tree, the compact trie of all suffixes. It ends with the Burrows-Wheeler transform, which reorders text to compress better and can be inverted, and the FM-index, which searches patterns directly over the reordered form without storing the text or full suffix array.
The suffix array
Work with text over an ordered alphabet, with zero-based indices, as in the code. Its last character is a sentinel appearing nowhere else and smaller than every other character. Write for the suffix starting at and for substring .
The sentinel has two effects. No suffix is a proper prefix of another (two distinct suffixes differ at latest at the shorter one’s ), so suffix order is always decided by a specific character, never by “shorter first.” And all comparisons in a loop advancing over two distinct suffixes stop before leaving the text, because matches only itself.
The example followed throughout the lesson is banana$, with :
| row | suffix | ||
|---|---|---|---|
| 0 | 6 | $ | 0 |
| 1 | 5 | a$ | 0 |
| 2 | 3 | ana$ | 1 |
| 3 | 1 | anana$ | 3 |
| 4 | 0 | banana$ | 0 |
| 5 | 4 | na$ | 0 |
| 6 | 2 | nana$ | 2 |
The last column, common prefix with the previous row’s suffix, will be carefully defined below. Notice already that the three suffixes beginning with a occupy rows 1 through 3 and the two beginning with ana rows 2 and 3. This is no accident.
Proof
For string , let be its prefix of length (or all of if shorter). Truncation is monotone: if lexicographically, then , because either and differ at position (and truncation preserves that difference), or agree in their first characters and their truncations are equal, or is a prefix of with , and then is a prefix of . If rows contain suffixes starting with and , then and truncating gives . Thus also starts with . The second claim is the opening observation: occurs at position if and only if it prefixes .
∎Binary pattern search
The interval is found with two binary searches: is the first row whose suffix truncated to characters is , and the first whose truncation is . Each step compares with a suffix in , so counting occurrences costs and listing them , with . For a genome, : a 100-base read is located in about 64 string comparisons without traversing the genome.
Manber and Myers, who introduced the suffix array in 1990 (journal version 1993), observed that many comparisons repeat work. If and are maintained during search, every intermediate suffix shares with at least characters (by the same monotonicity argument), and comparison can start there. This alone greatly speeds practice but worst case remains . If LCP between each possible binary-search midpoint and its interval endpoints is also precomputed (there are possible intervals, one per node of the implicit search tree), each step either advances in or is resolved without character comparisons, and search costs . These values come from the next section’s LCP array.
Construction by prefix doubling
How can suffixes be sorted without comparing them character by character? The idea, going back to Karp, Miller and Rosenberg (1972) and applied to suffixes by Manber and Myers (later refined by Larsson and Sadakane), is to sort by first character, then first 2, first 4, first 8, reusing the previous order each round.
Call the dense rank (0, 1, 2…) of the length- prefix of , namely truncated at text end, among the prefixes of that length. Two suffixes have the same if and only if their first characters match.
Proof
The length- prefix of is the concatenation of and , both truncated at text end ( empty if ). If , they differ at some position below (neither can be a proper prefix of the other: the shorter would end in the sentinel, appearing only in , and the other would also contain it at that position, so ). That position decides comparison of length- prefixes and of the first ranks. If and neither contains the sentinel, both have full length and comparison is decided by versus , namely versus (here , since does not reach the sentinel, so both are nonempty). If and they contain the sentinel, again . Therefore never decides a comparison between distinct positions: if , contains the sentinel and the first rank already resolved the order. The convention only defines the key at every position.
∎Thus one round looks at no characters: it sorts integer pairs in and assigns dense ranks. Sorting bounded-integer pairs needs no comparisons: use two-digit radix sort, one counting-sort pass on the second component and another stable pass on the first. Each pass costs .
See it work on mississippi. Bands group suffixes still tied: the animation breaks those bands apart.
mississippi$ and moves with each pass: the same tile at every step. Above is all the algorithm stores: each position's rank. The figure starts at round 1; return to the beginning with the player to see text order and round 0. In round 0 suffixes group by first character: five ranks with three tied groups. In each round a row's key is the pair of its rank (blue) and the rank of the suffix beginning positions later (orange); hover over a row to see those two cells above. Two stable counting-sort passes order pairs and split groups. For mississippi$, three rounds suffice, , because the longest common prefix of two suffixes, issi, has 4 characters. Try aaaaaaaaaaaa, the worst case, and dcbahgfe, which needs no rounds.Proof
After rounds, ranks are those of length- prefixes. Two distinct suffixes , tie if and only if their first characters match, namely if . Thus all ranks differ exactly when , and the smallest satisfying this is . Since , it is at most . Each round makes two counting-sort passes with keys in and one rank-assignment pass: operations and auxiliary integers.
∎Round count depends on text repetition, not size. In random text over an alphabet of size , maximum LCP is of order , so rounds suffice. In real source code with copied functions hundreds of characters long, around ten are needed (measured in the lab). Worst case is text such as , with .
SA-IS: linear-time construction
Some algorithms construct the suffix array in . The most used is SA-IS (Nong, Zhang and Chan, 2009). It classifies each suffix as S-type (smaller than the next, ) or L-type (larger), and calls S-type suffixes whose predecessor is L-type LMS. The key observation is induced sorting: if relative order of LMS suffixes is known, two linear array scans (left to right placing L-type, then right to left placing S-type) sort all others, because each L or S suffix is determined by its first character and following suffix, already placed. To sort LMS suffixes, reduce the problem to text of at most symbols, one per LMS substring, and recursively apply the same technique: . Production implementations (libsais, divsufsort) build a human genome array in minutes; prefix doubling is easier to program and vectorize, so we implement it.
The LCP array and Kasai’s algorithm
The suffix array orders; the LCP array measures how similar neighbors are.
In banana$, : ana$ and anana$ share ana, and na$ and nana$ share na. Storing LCP only between neighbors is no limitation, because any suffix pair’s LCP can be deduced.
Proof
Let be the minimum. () If each neighboring pair in the segment shares its first characters, equality transitivity makes all suffixes in the segment share those characters, especially the endpoints. () If endpoints shared characters, by truncation monotonicity (as in the interval theorem) every intermediate suffix would start with the same characters. In particular, the two neighbors of row attaining the minimum would, giving , a contradiction.
∎Thus any two suffixes’ LCP is a range minimum query: a sparse table on LCP answers in after preprocessing. This tool turns (SA, LCP) into a Swiss Army knife: compare any two suffixes, compute LCP of two text positions (for example, to check whether two fragments match in constant time without hashing), or simulate a suffix tree, as we will see.
Kasai’s algorithm
Calculating each by comparing both suffixes from the start costs in the worst case. Kasai, Lee, Arimura, Arikawa and Park (2001) observed that traversing suffixes in text order () instead of array order reuses almost all work from one suffix in the next.
The idea: if shares characters with its predecessor in order, removing the first character from both shows , smaller than , shares characters with it; ‘s predecessor lies between and , so shares at least as much. You will complete the proof in the guided exercise. With the lemma, the algorithm is almost obvious: traverse , compare with its predecessor starting at character (previous LCP minus one), rather than 0, and extend while they match.
Proof
Every matching comparison increments , and each failing comparison ends an iteration: there are at most of the latter. starts at 0, never exceeds and between iterations decreases by at most 1 (when is set to 0, but that occurs once, at suffix , last in text order). So total increments are at most plus total decrements, at most : increments. This is the same potential argument of amortized analysis, with as potential.
∎Three problems reduced to looking at LCP
With SA and LCP, many string problems that seem to require comparisons are solved by one linear pass over LCP.
Longest repeated substring. It is for row with maximum . If substring occurs at two positions , suffixes and share at least characters and, by the minimum theorem, so do all neighboring pairs between their rows: some is . Conversely, each is the length of a substring occurring at two positions.
Number of distinct substrings. Every substring is a suffix prefix. Traverse suffixes in array order and for each count prefixes that are not prefixes of any earlier suffix. By the minimum theorem, among suffixes preceding row , the one sharing most with is the immediate predecessor, with characters. New prefixes are those longer than . Excluding those containing the sentinel, for text of characters (without ):
For banana, .
Longest common substring of two texts. Concatenate with two separators appearing in neither text. The answer is the largest between adjacent rows whose suffixes start one in and one in . Why neighbors suffice: if occurs in at and in at , between rows of and suffix origin changes from to at some neighboring pair, which shares at least characters by the minimum theorem. Separator guarantees no common prefix extends from to . With and , the answer is anana, with LCP 5 between anana#ananas$ and ananas$, which are neighbors.
All three results are visible at a glance when LCP is plotted: it is a landscape where every peak is a repetition.
load_train and load_valid, a copied and edited function of 402 characters. Every offset inside the copied block gives another neighboring suffix pair, with LCP 402, 401, 400..., spread throughout the array. The selected row shows both neighboring suffixes with common prefix in blue (below, their two occurrences in text), and the list shows longest repetitions (the second is the functions' common header). Hover over other peaks. Raise the minimum-length threshold: what remains above it is what LLM-corpus-style deduplication would remove, marked below in the text. Compare with Don Quixote prose, whose longest repetition has 9 characters, and synthetic DNA, with a 60-base repeat copied three times (one copy with a mutation: see how it splits the peak).The figure reads like a copied-code detector: a peak of height is a fragment of characters appearing at least twice, and a plateau of width above a threshold is a fragment appearing times. One copy of length leaves a characteristic signature: peaks of heights , because every suffix of the repetition is repeated too. Thus listing distinct repetitions requires discarding those contained in one already listed (as the figure list and lab do), or keeping only left-maximal pairs, suffixes , with . In the Don Quixote paragraph the highest peak is hidalgo, 9 characters; in the small code module, 402. The distinct-substring count summarizes the same thing: the more repetitive a text, the farther it is from .
The suffix tree
If all suffixes of are inserted in a trie, every substring corresponds to a root path, and searching costs . But that trie has nodes in the worst case. Its compact version, where single-child chains merge into one edge, is the classic string-algorithm object.
With the sentinel, each suffix ends in its own leaf (none prefixes another). Since every internal node has at least two children, there are at most internal nodes. Each label is substring , stored with two integers, so the tree occupies words. Constants are high, however: with children, suffix links and labels, careful implementations use on the order of 10 to 20 bytes per character (Kurtz, 1999), versus 4 for a suffix array with 32-bit integers.
The relationship to what preceded is exact and worth drawing.
Proof
(1) A depth-first traversal visiting children in first-character order visits paths lexicographically. (2) The path to the common ancestor is the two suffixes’ longest common prefix: if they shared one more character, their paths would continue together along the same edge, unique for each initial character. (3) Subtree leaves are consecutive in depth-first traversal and are exactly suffixes beginning with the path label.
∎The converse is equally useful: from SA and LCP construct the tree in with a stack. Traverse rows in order, maintain the tree’s rightmost branch on the stack (nodes of increasing depth), and on reaching row close all nodes deeper than and attach the new leaf to a node of depth exactly , creating it if necessary. This is the same construction that produces the LCP array’s Cartesian tree, related to the LCA–RMQ reduction. Internal nodes are LCP intervals: maximal row segments with the same common prefix. Abouelhoda, Kurtz and Ohlebusch (2004) showed any algorithm traversing the tree bottom-up can be simulated with SA, LCP and that stack without building the tree: the enhanced suffix array.
mississippi$ with string depth vertical: each edge character occupies one step, so the root-to-leaf path spells its suffix top to bottom. Leaves appear left to right in suffix-array order (SA[r] row below). Pattern ssi follows an aquamarine path ending at a node of depth 3; its two leaves are array interval [10, 12), positions 5 and 2. Enter ss and the path ends halfway along an edge: the interval is the same. In orange, the common ancestor of two neighboring leaves: its depth equals their lcp row value. Select other values in that row and check they always match. Enter absent patterns and try aaaaaaa, whose tree is a caterpillar.Some algorithms construct the tree directly in linear time. The first was Weiner’s (1973), followed by McCreight’s (1976), inserting suffixes from longest to shortest. Ukkonen’s (1995) is best known because it is online: it reads text left to right and after has the (implicit, sentinel-free) suffix tree of that prefix. Reading a new character requires extending all current suffixes, naively per character. Ukkonen avoids this with three ideas: leaves have an open “to current end” label and extend themselves; suffix links (from the node labeled to that labeled ) jump between consecutive suffix extensions without descending from root; and once an extension finds the character already present, all following ones do too and the phase ends. A potential argument on active-point depth gives total for constant alphabets.
In practice the suffix array has almost entirely displaced the tree: it uses 2.5 to 5 times less space (4 bytes per character versus 10 to 20), is built by simpler faster algorithms, is contiguous in memory (cache-friendly), and with LCP does the same things. The tree remains the natural way to think about many string algorithms.
Lab: a suffix index for a code repository
First, the naive reference, used only to check results on small texts.
def sa_ingenuo(t):
"""Ordena las posiciones por su sufijo. Cada clave es una COPIA de t[i:]: O(n^2) memoria."""
return sorted(range(len(t)), key=lambda i: t[i:])
T = "banana$"
SA = sa_ingenuo(T)
print(" r SA[r] sufijo")
for r, i in enumerate(SA):
print(f"{r:2d} {i:5d} {T[i:]}")
for n in [10**3, 10**5, 10**6, 3 * 10**9]:
print(f"n = {n:>13,}: las claves ocupan {n * (n + 1) / 2:.2e} bytes")For , keys would occupy about bytes. Now prefix doubling from scratch in pure Python, with explicit counting sort so each round visibly compares no characters.
import random
def counting_sort(orden, clave, K):
"""Ordenación estable de las posiciones de `orden` según clave[i], con claves en [-1, K)."""
cuenta = [0] * (K + 2)
for i in orden:
cuenta[clave[i] + 2] += 1
for k in range(1, K + 2):
cuenta[k] += cuenta[k - 1] # cuenta[c + 1] = primera casilla libre de la clave c
salida = [0] * len(orden)
for i in orden:
c = clave[i] + 1
salida[cuenta[c]] = i
cuenta[c] += 1
return salida
def rangos_densos(orden, clave_de):
"""Rango 0, 1, 2... siguiendo `orden`: sube en 1 cada vez que cambia la clave."""
rango = [0] * len(orden)
for k in range(1, len(orden)):
rango[orden[k]] = rango[orden[k - 1]] + (clave_de(orden[k]) != clave_de(orden[k - 1]))
return rango
def sa_duplicacion(s):
"""Array de sufijos de s (s[-1] es el centinela, único y mínimo). Devuelve (SA, rondas)."""
n = len(s)
alfabeto = {c: k for k, c in enumerate(sorted(set(s)))}
c0 = [alfabeto[c] for c in s]
orden = counting_sort(range(n), c0, len(alfabeto)) # ronda 0: primer carácter
rango = rangos_densos(orden, lambda i: c0[i])
L, rondas = 1, 0
while rango[orden[-1]] < n - 1: # mientras queden empates
K = rango[orden[-1]] + 1
seg = [rango[i + L] if i + L < n else -1 for i in range(n)]
orden = counting_sort(range(n), seg, K) # pasada 1: segunda componente
orden = counting_sort(orden, rango, K) # pasada 2: primera (estable)
rango = rangos_densos(orden, lambda i: (rango[i], seg[i]))
L, rondas = 2 * L, rondas + 1
return orden, rondas
print("banana$ ", sa_duplicacion("banana$"))
print("mississippi$", sa_duplicacion("mississippi$"))
random.seed(1)
for _ in range(300):
t = "".join(random.choice("abc"[: random.randint(1, 3)]) for _ in range(random.randint(0, 40))) + "$"
assert sa_duplicacion(t)[0] == sa_ingenuo(t)
print("300 textos aleatorios: idéntico a la ordenación ingenua")
for nombre, t in [("aleatorio sobre {a,b}", "".join(random.choice("ab") for _ in range(4095)) + "$"),
("(ab)^2047 a", "ab" * 2047 + "a$"),
("a^4095", "a" * 4095 + "$")]:
sa, rondas = sa_duplicacion(t)
print(f"{nombre:22s} n = {len(t)}: {rondas:2d} rondas")The random 4096-character text needs few rounds because maximum LCP is small, about positions, while both periodic texts reach : the longest repeat determines round count. Next, Kasai with a comparison counter to check bound , and any two suffixes’ LCP using a sparse table.
def kasai(s, sa):
"""lcp[r] = LCP(s[sa[r-1]:], s[sa[r]:]) en O(n). Devuelve (lcp, comparaciones de caracteres)."""
n = len(s)
rango = [0] * n
for r, i in enumerate(sa):
rango[i] = r
lcp = [0] * n
h = comparaciones = 0
for i in range(n): # sufijos en orden de TEXTO, no en el del array
r = rango[i]
if r == 0: # el sufijo "$": no tiene predecesor
h = 0
continue
j = sa[r - 1] # su predecesor en el array de sufijos
while s[i + h] == s[j + h]: # el centinela único impide salirse del texto
h += 1
comparaciones += 1
comparaciones += 1 # la comparación que falla
lcp[r] = h
if h > 0:
h -= 1 # lema de Kasai: el siguiente lcp es al menos h - 1
return lcp, comparaciones
def lcp_ingenuo(t, sa):
out = [0]
for r in range(1, len(sa)):
a, b = t[sa[r - 1]:], t[sa[r]:]
h = 0
while a[h] == b[h]:
h += 1
out.append(h)
return out
T = "banana$"
SA = sa_duplicacion(T)[0]
print("banana$: lcp =", kasai(T, SA)[0])
for nombre, t in [("aleatorio sobre {a,b}", "".join(random.choice("ab") for _ in range(4095)) + "$"),
("a^4095", "a" * 4095 + "$"),
("(abc)^1365", "abc" * 1365 + "$")]:
sa = sa_duplicacion(t)[0]
lcp, comp = kasai(t, sa)
assert lcp == lcp_ingenuo(t, sa)
print(f"{nombre:22s} comparaciones / n = {comp / len(t):.3f} (cota: 3)")
# LCP de dos sufijos cualesquiera: mínimo en un tramo del array LCP, con una tabla dispersa
def tabla_dispersa(a):
tabla = [list(a)]
k = 1
while 2 * k <= len(a):
prev = tabla[-1]
tabla.append([min(prev[i], prev[i + k]) for i in range(len(a) - 2 * k + 1)])
k *= 2
return tabla
def lcp_par(tabla, rango, i, j):
"""LCP de los sufijos que empiezan en las posiciones i != j, en O(1)."""
a, b = sorted((rango[i], rango[j]))
k = (b - a).bit_length() - 1 # tramo (a, b] = dos bloques de 2^k que se solapan
return min(tabla[k][a + 1], tabla[k][b - 2**k + 1])
t = "".join(random.choice("ab") for _ in range(2000)) + "$"
sa = sa_duplicacion(t)[0]
lcp = kasai(t, sa)[0]
rango = [0] * len(t)
for r, i in enumerate(sa):
rango[i] = r
tabla = tabla_dispersa(lcp)
for _ in range(2000):
i, j = random.sample(range(len(t)), 2)
h = 0
while t[i + h] == t[j + h]:
h += 1
assert lcp_par(tabla, rango, i, j) == h
print("2000 pares aleatorios: el mínimo del tramo coincide con el LCP comparado a mano")All three texts give almost exactly 2 comparisons per character, not 3: about failures (one per iteration) and matches, because overall rises as much as it falls and falls at most 1 per iteration. Even in , where the first iteration performs 4094 consecutive comparisons, later ones do almost none.
Now the real index, on source code from a dozen Python standard-library modules (about 440 KB, read in Pyodide with inspect). For speed, each doubling round is vectorized with NumPy. Pair , with both components in , is packed into integer : a two-digit base- number, whose order is pair lexicographic order, exactly what two-digit radix sort orders. One argsort per round then suffices (NumPy internally uses its own sort, not counting sort). Two consecutive stable argsort passes, first on the second component then the first, would literally translate the two passes and give the same order, but are more than twice as slow. The sentinel is byte 0, absent from source code and smaller than every other byte.
import inspect, math, time
import numpy as np
import json.decoder, json.encoder, textwrap, argparse, collections, dataclasses
import fractions, statistics, string, csv, heapq, bisect
modulos = [json.decoder, json.encoder, textwrap, argparse, collections, dataclasses,
fractions, statistics, string, csv, heapq, bisect]
corpus = "".join(inspect.getsource(m) for m in modulos).encode("utf-8")
assert 0 not in corpus
datos = corpus + b"\0" # el centinela
def sa_numpy(s):
"""Duplicación de prefijos con NumPy: cada ronda ordena los pares (rango, seg) como enteros de dos cifras."""
n = len(s)
rango = np.unique(s, return_inverse=True)[1].astype(np.int64)
L, rondas = 1, 0
while rango.max() < n - 1:
seg = np.full(n, -1, dtype=np.int64)
seg[: n - L] = rango[L:]
o = np.argsort(rango * (n + 1) + seg + 1) # el par como número de dos cifras en base n + 1
a, b = rango[o], seg[o]
nuevo = np.empty(n, dtype=np.int64)
nuevo[o] = np.concatenate(([0], np.cumsum((a[1:] != a[:-1]) | (b[1:] != b[:-1]))))
rango, L, rondas = nuevo, 2 * L, rondas + 1
return np.argsort(rango), rondas
t0 = time.perf_counter()
SA_np, rondas = sa_numpy(np.frombuffer(datos, dtype=np.uint8).astype(np.int64))
t1 = time.perf_counter()
SA_c = SA_np.tolist()
LCP_c, comp = kasai(datos, SA_c) # indexar bytes devuelve enteros
t2 = time.perf_counter()
n = len(datos)
print(f"{len(corpus):,} bytes: SA con {rondas} rondas en {t1 - t0:.2f} s, Kasai en {t2 - t1:.2f} s "
f"({comp / n:.2f} comparaciones por byte)")
print(f"LCP máximo = {max(LCP_c)}, y ceil(log2(LCP máx + 1)) = {math.ceil(math.log2(max(LCP_c) + 1))}")
def intervalo(datos, SA, p):
"""[sp, ep): filas cuyos sufijos empiezan por p, con dos búsquedas binarias. O(m log n)."""
m, lo, hi = len(p), 0, len(SA)
while lo < hi: # primera fila con prefijo >= p
mid = (lo + hi) // 2
if datos[SA[mid]: SA[mid] + m] < p: lo = mid + 1
else: hi = mid
sp, hi = lo, len(SA)
while lo < hi: # primera fila con prefijo > p
mid = (lo + hi) // 2
if datos[SA[mid]: SA[mid] + m] <= p: lo = mid + 1
else: hi = mid
return sp, lo
print()
for p in [b"def __init__(self", b"raise TypeError", b"return NotImplemented", b"yield from"]:
sp, ep = intervalo(datos, SA_c, p)
print(f"{p.decode():24s} {ep - sp:4d} apariciones (bytes.count: {corpus.count(p)})")
# las repeticiones más largas, sin listar las que caben dentro de otra ya listada
print("\nLos fragmentos repetidos más largos:")
lcp_np = np.array(LCP_c)
vistos = []
for r in np.argsort(-lcp_np, kind="stable"):
h = LCP_c[r]
frag = datos[SA_c[r]: SA_c[r] + h]
if any(frag in v for v in vistos):
continue
vistos.append(frag)
print(f" {h:4d} bytes, posiciones {SA_c[r - 1]:6d} y {SA_c[r]:6d}: {frag[:58]!r}")
if len(vistos) == 4:
break
m = len(corpus)
distintas = m * (m + 1) // 2 - sum(LCP_c)
print(f"\nsubcadenas: {m * (m + 1) // 2:.4e} en total, {distintas:.4e} distintas; "
f"suma del LCP = {int(lcp_np.sum()):,} (lcp medio entre vecinos: {lcp_np.mean():.1f} bytes)")
# fracción de bytes dentro de alguna repetición de al menos 50 bytes (lo que miraría una deduplicación)
marca = np.zeros(n + 1, dtype=np.int64)
filas = np.nonzero(lcp_np >= 50)[0]
for inicio in (SA_np[filas - 1], SA_np[filas]): # las dos apariciones de cada par de vecinos
np.add.at(marca, inicio, 1) # +1 al empezar el tramo repetido
np.add.at(marca, inicio + lcp_np[filas], -1) # -1 al acabar
cubierto = np.count_nonzero(np.cumsum(marca)[:m])
print(f"bytes dentro de repeticiones de >= 50 bytes: {cubierto:,} ({100 * cubierto / m:.1f} %)")The 441,876 bytes need 10 rounds, exactly with maximum LCP of 558 bytes, as the theorem predicts, and Kasai again makes 2 comparisons per byte. Binary search counts occurrences just like bytes.count without traversing the corpus. Longest repetitions are code copied within one module: 558 bytes of list and tuple handling repeated by json.encoder in two internal functions, 499 bytes of docstring and code shared by bisect_left and bisect_right, 438 bytes of data and bandwidth validation shared by kde and kde_random in statistics, and 435 bytes of constructors of _StoreAction and _AppendAction in argparse. In total, 23.1% of bytes lie inside some repetition of at least 50 bytes: substring deduplication like Lee and colleagues’ would remove all but one copy.
The Burrows-Wheeler transform
The suffix array occupies integers, 4 to 8 times more than the text itself. For a genome this is 12 GB or more. The rest of the lesson constructs an index occupying less than the text, starting from a transform invented for compression.
That is, is the character preceding the suffix of row . For banana$, with , BWT is annb$aa (characters at positions ), and $aaabnn is simply sorted text. Constructed this way, BWT costs the same as the suffix array.
Why it helps compression
BWT is a permutation of characters of : same length and exactly the same frequencies, so its order-0 entropy is unchanged. What changes is locality. Rows are sorted by what follows each position, so adjacent rows have similar right contexts and the character preceding a context is highly predictable. In Spanish text, most rows beginning with ue are preceded by q (from que ); in Python code, almost all beginning with elf. are preceded by s. In BWT these characters group into long runs.
Simple transforms exploit runs. Move-to-front (MTF) replaces each character by its position in a list reordered by moving the last used to the front: a run becomes a sequence of zeros and the output-symbol distribution concentrates on small values. An order-0 entropy coder such as Huffman then suffices. This is bzip2’s recipe: BWT in 100–900 KB blocks, MTF, zero-run encoding and Huffman. Manzini (2001) proved that with run encoding included, this scheme’s output occupies at most a constant times times the text’s order- empirical entropy (in a slightly modified variant, ), plus lower-order terms, for all simultaneously and without knowing : context sorting does what an explicit model does in other compressors.
Invert BWT: the LF function
Surprisingly, sorted BWT can be undone while retaining nothing more than the sentinel. The key is an order property of the two columns.
The proof is an order observation: rows ending in , shifted so moves to the front, retain their relative order because they all now start with the same and the remainder preserves its order. You will prove it step by step in an exercise. In , LF is simply : it moves one text position backward. But it is calculated without SA, using and on .
LF reconstructs text right to left. Row 0 is the rotation starting with , so its is , the last character before the sentinel. Applying LF goes back one position: , and so on. In banana$: row 0 yields a; yields n; yields a; in total read a, n, a, n, a, b: text backwards. There are steps, each with a rank query.
The FM-index: search transformed text
Ferragina and Manzini (2000) observed LF not only moves backwards in text: it also extends a pattern to the left. If rows are rotations starting with , those starting with are LF images of interval rows whose is , and by LF correspondence those images are consecutive.
Proof
A rotation starts with if and only if it is the LF image of a row starting with and ending in : shifting a rotation moves its last character to the front. Rows of with are occurrences of in with occurrence index between (inclusive) and (exclusive). By LF correspondence, the -th of moves to row . Their images are therefore rows with in that range, the stated interval. If no exists in , the endpoints coincide and the interval is empty.
∎Watch the search for abra in abracadabra$. Text is never needed: toggle it on and off.
abracadabra$, with column , a faded center and column (the BWT, ard$rcaaaabb). At right, again: LF arrows land there. The figure starts at the second processed letter, r; return to the beginning with the player and step through. Pattern abra is read right to left: first a moves from to ; then r: has two rs inside the interval and none above, so rows jump to ; then b gives and finally a gives : two occurrences. Enable ‘Hide what is not stored’: search uses only and . At the end each row locates its position by walking LF to a row with sampled SA (purple); change sampling and watch steps grow. Try banana · nab, which becomes empty.Constant-time rank: blocks
All cost is in . Counting by scanning would cost per query. The standard solution is checkpoints: every positions, store for each character how many occurrences appeared so far. A query takes the checkpoint preceding and counts within at most characters. With characters and 32-bit counters, checkpoints occupy bits. For DNA ( plus sentinel) with this is 2 bits per base, as much as packed BWT itself; counting within a block uses bit operations and popcount on 64-bit words in constant time. Large alphabets (text, tokens) use a wavelet tree, answering rank in with bits plus lower-order terms.
Locate: sample the suffix array
Backward search counts but does not say where. For that, store only in rows whose value is a multiple of , namely text positions . To locate row , apply LF until reaching a sampled row: after steps the position is , and if its stored value is the answer is . Since samples are every text positions, at most steps suffice. To determine whether a row is sampled and where its value lies in the sample, use an -bit vector marking those rows, with rank support. The sample uses bits: with and 32-bit integers, one bit per character, and the marker vector another bit per character.
For a human genome of bases: BWT packed at 2 bits per base occupies about 775 MB; checkpoints with another 775 MB; samples with about 390 MB, and marker vector another 390 MB. Total about 2.3 GB, versus 3.1 GB for ASCII text and over 12 GB for the full suffix array. Ferragina and Manzini proved that block-compressing BWT yields an entire index of bits plus lower-order terms, where is empirical entropy of order ; later wavelet-tree versions reduce this to . This index fits in compressed-text space and still answers queries.
Lab: BWT and FM-index
BWT is read directly from the corpus suffix array, and inversion only needs .
from collections import Counter
def bwt(datos, SA):
"""L[r] = datos[SA[r] - 1]; con SA[r] = 0, datos[-1] es el centinela."""
return bytes(datos[i - 1] for i in SA)
def invertir_bwt(L):
"""Reconstruye el texto (con su centinela) a partir de L, de derecha a izquierda, con LF."""
n = len(L)
cuenta = [0] * 256
rank_en = [0] * n # rank_en[r] = apariciones de L[r] en L[0, r)
for r, c in enumerate(L):
rank_en[r] = cuenta[c]
cuenta[c] += 1
C, acc = [0] * 256, 0
for c in range(256):
C[c], acc = acc, acc + cuenta[c]
out = bytearray(n)
out[n - 1] = min(L) # el centinela es el menor carácter
r = 0 # la fila 0 es la rotación que empieza por el centinela
for k in range(n - 2, -1, -1):
out[k] = L[r]
r = C[L[r]] + rank_en[r] # LF: un carácter hacia atrás en el texto
return bytes(out)
b = b"banana$"
Lb = bwt(b, sa_duplicacion(b)[0])
print("BWT de banana$:", Lb.decode(), " invertida:", invertir_bwt(Lb).decode())
L_c = bwt(datos, SA_c)
assert invertir_bwt(L_c) == datos
print(f"corpus: BWT de {len(L_c):,} bytes, invertida sin errores")
def rachas(x):
return 1 + sum(x[k] != x[k - 1] for k in range(1, len(x)))
print(f"rachas de caracteres iguales: texto {rachas(datos):,}, BWT {rachas(L_c):,}")
# el contexto ordena: qué precede a «elf.» y a «turn »
for ctx in [b"elf.", b"turn ", b"rgs"]:
sp, ep = intervalo(datos, SA_c, ctx)
comunes = Counter(L_c[sp:ep]).most_common(3)
print(f"antes de {ctx!r:9}: {ep - sp:5d} filas seguidas en la BWT; los más frecuentes:",
[(chr(c), k) for c, k in comunes])The 1046 rows beginning with elf. lie together in BWT and all are preceded by s; of 828 beginning with turn , 827 are preceded by e (from return ), and all 412 of rgs by a (from args). This is the run mechanism: corpus BWT has 130,444 equal-character runs, versus 345,697 in original text. Now the full index, with block rank and sampled SA.
import time
import numpy as np
class FMIndex:
def __init__(self, datos, SA, b=64, s=32):
self.L = bwt(datos, SA)
self.n, self.b, self.s = len(self.L), b, s
Lnp = np.frombuffer(self.L, dtype=np.uint8)
alfabeto = np.unique(Lnp)
cuenta = np.bincount(Lnp, minlength=256)
self.C = {int(c): int(cuenta[:c].sum()) for c in alfabeto}
# puntos de control: cp[c][k] = apariciones de c en L[0, k*b)
self.cp = {}
for c in alfabeto:
acum = np.concatenate(([0], np.cumsum(Lnp == c)))
self.cp[int(c)] = acum[::b].astype(np.int32)
# muestra del SA en las posiciones de texto múltiplos de s
SAnp = np.asarray(SA)
filas = np.nonzero(SAnp % s == 0)[0]
self.muestra = dict(zip(filas.tolist(), SAnp[filas].tolist()))
def rank(self, c, i):
"""Apariciones de c en L[0, i): punto de control + recuento en menos de b bytes."""
k = i // self.b
return int(self.cp[c][k]) + self.L.count(c, k * self.b, i)
def contar(self, p):
"""Búsqueda hacia atrás: intervalo [sp, ep) de p. 2 len(p) consultas de rank."""
sp, ep = 0, self.n
for c in reversed(p):
if c not in self.C:
return 0, 0
sp, ep = self.C[c] + self.rank(c, sp), self.C[c] + self.rank(c, ep)
if sp >= ep:
return sp, sp
return sp, ep
def lf(self, r):
c = self.L[r]
return self.C[c] + self.rank(c, r)
def localizar(self, p):
sp, ep = self.contar(p)
posiciones, pasos = [], 0
for r in range(sp, ep):
k = 0
while r not in self.muestra:
r, k = self.lf(r), k + 1
posiciones.append(self.muestra[r] + k)
pasos += k
return sorted(posiciones), pasos
t0 = time.perf_counter()
fm = FMIndex(datos, SA_c)
print(f"construcción a partir del SA: {time.perf_counter() - t0:.2f} s")
for p in [b"def __init__(self", b"raise TypeError", b"return NotImplemented", b"yield from", b"no aparece nunca"]:
sp, ep = fm.contar(p)
sp2, ep2 = intervalo(datos, SA_c, p)
assert (ep - sp) == (ep2 - sp2)
pos, pasos = fm.localizar(p)
assert pos == sorted(SA_c[sp2:ep2])
media = pasos / max(1, len(pos))
print(f"{p.decode():24s} {ep - sp:4d} apariciones, {media:5.1f} pasos LF por posición (máximo {fm.s - 1})")
n = fm.n
sigma = len(fm.C)
print(f"\nn = {n:,}, sigma = {sigma}")
print(f"array de sufijos con int32: {4 * n / 1e6:7.2f} MB")
print(f"FM-index: BWT (1 byte por carácter): {n / 1e6:7.2f} MB")
print(f" puntos de control (b=64): {4 * sigma * (n // 64 + 1) / 1e6:7.2f} MB")
print(f" muestra del SA (s=32): {4 * len(fm.muestra) / 1e6:7.2f} MB")Counts match binary search and positions match the full suffix array, with about 15 or 16 LF steps per position on average for the three frequent patterns, near , the mean if positions fall randomly relative to samples (with 11 occurrences of yield from, the sample is too small to average). Memory accounting has a surprise: with 106 distinct bytes in the corpus, checkpoints with occupy 2.93 MB, nearly seven times BWT and more than the suffix array itself (1.77 MB). Storing one 32-bit counter per alphabet character every 64 positions costs bytes per position. This motivates wavelet trees for text and bit blocks for DNA, where . Finally, verify BWT does not compress on its own.
import bz2, zlib, math
from collections import Counter
def h0(x):
"""Entropía de orden 0 en bits por byte."""
n = len(x)
return -sum(k / n * math.log2(k / n) for k in Counter(x).values())
def mtf(x):
"""Move-to-front: cada byte se sustituye por su posición en una lista que se reordena."""
tabla = list(range(256))
out = bytearray(len(x))
for k, c in enumerate(x):
j = tabla.index(c)
out[k] = j
if j:
del tabla[j]
tabla.insert(0, c)
return bytes(out)
texto, L = datos, fm.L
print(f"H0 del texto: {h0(texto):.3f} bits/byte")
print(f"H0 de la BWT: {h0(L):.3f} bits/byte (la misma: es una permutación)")
m_t, m_l = mtf(texto), mtf(L)
print(f"H0 de MTF(texto): {h0(m_t):.3f} bits/byte ceros: {m_t.count(0) / len(m_t):.1%}")
print(f"H0 de MTF(BWT): {h0(m_l):.3f} bits/byte ceros: {m_l.count(0) / len(m_l):.1%}")
print()
print(f"original: {len(corpus):8,} bytes")
print(f"bz2 (BWT+MTF+...){len(bz2.compress(corpus, 9)):8,} bytes")
print(f"zlib (LZ77) {len(zlib.compress(corpus, 9)):8,} bytes")
print(f"H0(MTF(BWT)) x n {int(h0(m_l) * len(L) / 8):8,} bytes (Huffman de orden 0 tras MTF, sin cabeceras)")BWT’s order-0 entropy is the text’s, exactly 4.494 bits per byte. MTF applied to text raises it to 4.764 because without locality MTF only shuffles symbols; applied to BWT it lowers it to 2.017, less than half, with 70.5% zeros. That jump is almost all bzip2’s compression, which also encodes zero runs and uses multiple Huffman tables: it reduces 441,876 bytes to 95,282, 4.6 times smaller, versus zlib’s 110,389, based on Lempel-Ziv with a 32 KB window.
In practice
| Need | Tool |
|---|---|
| Build SA (and LCP) of bytes or integers | libsais (optimized SA-IS, also LCP and BWT), divsufsort; in Python, pydivsufsort |
| Compressed indexes (FM-index, wavelet trees, CSA) | sdsl-lite (C++), with FM-index, wavelet trees and compressed suffix arrays |
| Align DNA reads | BWA, Bowtie 2 (genome FM-index) |
| Deduplicate a text corpus | deduplicate-text-datasets (Lee and colleagues, Rust, with suffix arrays) |
| Count arbitrary-length -grams | infini-gram (suffix arrays over tokens) |
| Block compression | bz2 in the standard library (BWT + MTF + Huffman) |
For text, an important practical decision is which symbols to index. On bytes, searching a multibyte Unicode character works directly (UTF-8 preserves code-point order) and the alphabet is small. On tokenizer tokens, the alphabet has tens of thousands of symbols, text integers occupy 2 or 4 bytes, and the suffix array is shorter (one token covers several bytes), as LLM deduplication and -gram counting tools do. In either case, when the suffix array does not fit in RAM, build it in pieces and merge on disk using the external-memory model principles.
Common mistakes
Exercises
Step 1 of 5. What do you know about versus ?
Step 1 of 4. Why does imply ?
subcadenas_distintas(t), returning the number of distinct nonempty substrings of string t (which does not contain the character '\x00'), using a suffix array and LCP array. Tests compare with the set of all substrings in small texts and test 5000-character texts, where enumerating substrings is impractical. You may use sa_duplicacion and kasai from the lab or write your own.def subcadenas_distintas(t):
"""Número de subcadenas distintas no vacías de t."""
m = len(t)
# tu código: array de sufijos de t + centinela, array LCP y la fórmula del recuento
return m * (m + 1) // 2Summary
- The suffix array is the permutation sorting suffixes of ; pattern occurrences form a row interval found by two binary searches in , or with LCP information.
- Prefix doubling sorts by the first characters using rank pairs and radix sort: rounds of . SA-IS does it in with induced sorting.
- The LCP array stores neighbors’ common prefix; an arbitrary pair’s LCP is a range minimum (RMQ). Kasai computes it in by traversing in text order, because LCP falls by at most 1 from one suffix to the next.
- Longest repetition, distinct substrings () and longest common substring of two texts are solved with one LCP pass.
- The suffix tree is the compact trie of suffixes, with nodes; its ordered leaves are SA and common ancestors’ string depth for neighboring leaves is LCP. Ukkonen builds it online in linear time, but SA with LCP does the same using far less memory.
- BWT is the last column of sorted rotations, . It does not compress on its own but groups characters with the same context, exploited by MTF plus entropy coding (bzip2). It is inverted using .
- The FM-index counts occurrences of with rank queries (backward search), locates using LF to an SA sampled every text positions, and occupies less than uncompressed text (with compressed BWT, on the order of compressed text): it is the index used by genomic aligners.