Module contents
Lesson 13 of 33Advanced 110 min

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 O(n+m)\bigO(n + m) 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 mm, pattern length, and almost nothing on nn. 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 3.1×1093.1\times 10^9 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 nn-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 TT is a prefix of some suffix of TT. Thus “does PP occur in TT?” is the same as “is PP a prefix of some suffix?”. Alphabetically sort the nn suffixes and all starting with PP are adjacent, so a binary search finds the block. The lesson’s central object is that order, stored as a permutation of {0,…,n−1}\{0, \dots, n - 1\}: it occupies nn integers, not n2/2n^2/2 characters.

The lesson constructs that array (by prefix doubling, in O(nlog⁡n)\bigO(n \log n)), adds the LCP array (Kasai, in O(n)\bigO(n)), 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 T=t0t1⋯tn−1T = t_0 t_1 \cdots t_{n-1} over an ordered alphabet, with zero-based indices, as in the code. Its last character is a sentinel tn−1=$t_{n-1} = \texttt{\textdollar} appearing nowhere else and smaller than every other character. Write Ti=titi+1⋯tn−1T_i = t_i t_{i+1} \cdots t_{n-1} for the suffix starting at ii and T[i,j)T[i, j) for substring ti⋯tj−1t_i \cdots t_{j-1}.

The sentinel has two effects. No suffix is a proper prefix of another (two distinct suffixes differ at latest at the shorter one’s $\texttt{\textdollar}), 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 $\texttt{\textdollar} matches only itself.

The example followed throughout the lesson is banana$, with n=7n = 7:

row rrSA[r]\mathrm{SA}[r]suffix TSA[r]T_{\mathrm{SA}[r]}lcp[r]\mathrm{lcp}[r]
06$0
15a$0
23ana$1
31anana$3
40banana$0
54na$0
62nana$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 XX, let X(m)X^{(m)} be its prefix of length mm (or all of XX if shorter). Truncation is monotone: if X≤YX \le Y lexicographically, then X(m)≤Y(m)X^{(m)} \le Y^{(m)}, because either XX and YY differ at position k<mk < m (and truncation preserves that difference), or agree in their first mm characters and their truncations are equal, or XX is a prefix of YY with ∣X∣<m\abs{X} < m, and then X(m)=XX^{(m)} = X is a prefix of Y(m)Y^{(m)}. If rows r1<r2r_1 < r_2 contain suffixes starting with PP and r1<r<r2r_1 < r < r_2, then TSA[r1]<TSA[r]<TSA[r2]T_{\mathrm{SA}[r_1]} < T_{\mathrm{SA}[r]} < T_{\mathrm{SA}[r_2]} and truncating gives P≤TSA[r](m)≤PP \le T_{\mathrm{SA}[r]}^{(m)} \le P. Thus TSA[r]T_{\mathrm{SA}[r]} also starts with PP. The second claim is the opening observation: PP occurs at position ii if and only if it prefixes TiT_i.

∎

The interval is found with two binary searches: spsp is the first row whose suffix truncated to mm characters is ≥P\ge P, and epep the first whose truncation is >P> P. Each step compares PP with a suffix in O(m)\bigO(m), so counting occurrences costs O(mlog⁡n)\bigO(m \log n) and listing them O(mlog⁡n+occ)\bigO(m \log n + \mathrm{occ}), with occ=ep−sp\mathrm{occ} = ep - sp. For a genome, log⁡2n≈32\log_2 n \approx 32: 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 ℓ=LCP(P,TSA[lo])\ell = \mathrm{LCP}(P, T_{\mathrm{SA}[lo]}) and h=LCP(P,TSA[hi])h = \mathrm{LCP}(P, T_{\mathrm{SA}[hi]}) are maintained during search, every intermediate suffix shares with PP at least min⁡(ℓ,h)\min(\ell, h) characters (by the same monotonicity argument), and comparison can start there. This alone greatly speeds practice but worst case remains O(mlog⁡n)\bigO(m \log n). If LCP between each possible binary-search midpoint and its interval endpoints is also precomputed (there are O(n)\bigO(n) possible intervals, one per node of the implicit search tree), each step either advances in PP or is resolved without character comparisons, and search costs O(m+log⁡n)\bigO(m + \log n). These values come from the next section’s LCP array.

Construction by prefix doubling

How can nn 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 rankL[i]\mathrm{rank}_L[i] the dense rank (0, 1, 2…) of the length-LL prefix of TiT_i, namely T[i,i+L)T[i, i + L) truncated at text end, among the nn prefixes of that length. Two suffixes have the same rankL\mathrm{rank}_L if and only if their first LL characters match.

Proof

The length-2L2L prefix of TiT_i is the concatenation of Ai=T[i,i+L)A_i = T[i, i + L) and Bi=T[i+L,i+2L)B_i = T[i + L, i + 2L), both truncated at text end (BiB_i empty if i+L≥ni + L \ge n). If Ai≠AjA_i \ne A_j, they differ at some position below LL (neither can be a proper prefix of the other: the shorter would end in the sentinel, appearing only in tn−1t_{n-1}, and the other would also contain it at that position, so i=ji = j). That position decides comparison of length-2L2L prefixes and of the first ranks. If Ai=AjA_i = A_j and neither contains the sentinel, both have full length LL and comparison is decided by BiB_i versus BjB_j, namely rankL[i+L]\mathrm{rank}_L[i + L] versus rankL[j+L]\mathrm{rank}_L[j + L] (here i+L<ni + L < n, since AiA_i does not reach the sentinel, so both BB are nonempty). If Ai=AjA_i = A_j and they contain the sentinel, again i=ji = j. Therefore −1-1 never decides a comparison between distinct positions: if i+L≥ni + L \ge n, AiA_i 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 nn integer pairs in [−1,n)[-1, n) 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 O(n)\bigO(n).

See it work on mississippi. Bands group suffixes still tied: the animation breaks those bands apart.

InteractivePrefix-doubling construction
Stored by the algorithm: rank[i] per position0m·1i·2s·3s·4i·5s·6s·7i·8p·9p·10i·11$·Trankisuffix T[i:]rank0mississippi$·1ississippi$·2ssissippi$·3sissippi$·4issippi$·5ssippi$·6sippi$·7ippi$·8ppi$·9pi$·10i$·11$·
  • first half: rank[i]
  • second half: rank[i + L]
  • suffixes still tied
step 1 / 15
The 12 suffixes of TT in text order. Each row is a suffix identified by starting position ii: the suffix array stores only these positions, never the strings.
Enter text (up to 14 characters)
Prefix length LL0
Distinct ranks· / 12
Doubling round0
Counting-sort passes0
Required rounds ⌈log⁡2(LCPmax⁡+1)⌉\lceil \log_2(\mathrm{LCP}_{\max} + 1) \rceil3 (max LCP = 4)
Each row is a suffix of 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 LL 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, L=1,2,4L = 1, 2, 4, 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 kk rounds, ranks are those of length-L=2kL = 2^k prefixes. Two distinct suffixes TiT_i, TjT_j tie if and only if their first LL characters match, namely if LCP(Ti,Tj)≥L\mathrm{LCP}(T_i, T_j) \ge L. Thus all ranks differ exactly when 2k>ℓmax⁡2^k > \ell_{\max}, and the smallest kk satisfying this is ⌈log⁡2(ℓmax⁡+1)⌉\lceil \log_2(\ell_{\max} + 1) \rceil. Since ℓmax⁡≤n−2\ell_{\max} \le n - 2, it is at most ⌈log⁡2n⌉\lceil \log_2 n \rceil. Each round makes two counting-sort passes with keys in [−1,n)[-1, n) and one rank-assignment pass: O(n)\bigO(n) operations and O(n)\bigO(n) auxiliary integers.

∎

Round count depends on text repetition, not size. In random text over an alphabet of size σ\sigma, maximum LCP is of order 2log⁡σn2\log_\sigma n, so O(log⁡log⁡n)\bigO(\log \log n) 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 an−1$\texttt{a}^{n-1}\texttt{\textdollar}, with ℓmax⁡=n−2\ell_{\max} = n - 2.

SA-IS: linear-time construction

Some algorithms construct the suffix array in O(n)\bigO(n). The most used is SA-IS (Nong, Zhang and Chan, 2009). It classifies each suffix as S-type (smaller than the next, Ti<Ti+1T_i < T_{i+1}) 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 n/2n/2 symbols, one per LMS substring, and recursively apply the same technique: T(n)=T(n/2)+O(n)=O(n)T(n) = T(n/2) + \bigO(n) = \bigO(n). 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$, lcp=[0,0,1,3,0,0,2]\mathrm{lcp} = [0, 0, 1, 3, 0, 0, 2]: 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 hh be the minimum. (≥\ge) If each neighboring pair in the segment shares its first hh characters, equality transitivity makes all suffixes in the segment share those hh characters, especially the endpoints. (≤\le) If endpoints shared h+1h + 1 characters, by truncation monotonicity (as in the interval theorem) every intermediate suffix would start with the same h+1h + 1 characters. In particular, the two neighbors of row cc attaining the minimum would, giving lcp[c]≥h+1\mathrm{lcp}[c] \ge h + 1, a contradiction.

∎

Thus any two suffixes’ LCP is a range minimum query: a sparse table on LCP answers in O(1)\bigO(1) after O(nlog⁡n)\bigO(n \log n) 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 lcp[r]\mathrm{lcp}[r] by comparing both suffixes from the start costs O(n2)\bigO(n^2) in the worst case. Kasai, Lee, Arimura, Arikawa and Park (2001) observed that traversing suffixes in text order (T0,T1,T2,…T_0, T_1, T_2, \dots) instead of array order reuses almost all work from one suffix in the next.

The idea: if TiT_i shares h≥1h \ge 1 characters with its predecessor TjT_j in order, removing the first character from both shows Tj+1T_{j+1}, smaller than Ti+1T_{i+1}, shares h−1h - 1 characters with it; Ti+1T_{i+1}‘s predecessor lies between Tj+1T_{j+1} and Ti+1T_{i+1}, so shares at least as much. You will complete the proof in the guided exercise. With the lemma, the algorithm is almost obvious: traverse i=0,1,…,n−1i = 0, 1, \dots, n - 1, compare TiT_i with its predecessor starting at character hh (previous LCP minus one), rather than 0, and extend while they match.

Proof

Every matching comparison increments hh, and each failing comparison ends an iteration: there are at most nn of the latter. hh starts at 0, never exceeds nn and between iterations decreases by at most 1 (when rank[i]=0\mathrm{rank}[i] = 0 is set to 0, but that occurs once, at suffix $\texttt{\textdollar}, last in text order). So total increments are at most nn plus total decrements, at most nn: 2n2n increments. This is the same potential argument of amortized analysis, with hh as potential.

∎

Three problems reduced to looking at LCP

With SA and LCP, many string problems that seem to require O(n2)\bigO(n^2) comparisons are solved by one linear pass over LCP.

Longest repeated substring. It is T[SA[r],SA[r]+lcp[r])T[\mathrm{SA}[r], \mathrm{SA}[r] + \mathrm{lcp}[r]) for row rr with maximum lcp[r]\mathrm{lcp}[r]. If substring uu occurs at two positions i≠ji \ne j, suffixes TiT_i and TjT_j share at least ∣u∣\abs{u} characters and, by the minimum theorem, so do all neighboring pairs between their rows: some lcp[r]\mathrm{lcp}[r] is ≥∣u∣\ge \abs{u}. Conversely, each lcp[r]\mathrm{lcp}[r] 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 rr, the one sharing most with TSA[r]T_{\mathrm{SA}[r]} is the immediate predecessor, with lcp[r]\mathrm{lcp}[r] characters. New prefixes are those longer than lcp[r]\mathrm{lcp}[r]. Excluding those containing the sentinel, for text of m=n−1m = n - 1 characters (without $\texttt{\textdollar}):

#{subcadenas distintas no vacıˊas}=m(m+1)2−∑rlcp[r].\#\{\text{subcadenas distintas no vacías}\} = \frac{m(m+1)}{2} - \sum_{r} \mathrm{lcp}[r].

For banana, 21−6=1521 - 6 = 15.

Longest common substring of two texts. Concatenate S=A # B $S = A\,\texttt{\#}\,B\,\texttt{\textdollar} with two separators appearing in neither text. The answer is the largest lcp[r]\mathrm{lcp}[r] between adjacent rows whose suffixes start one in AA and one in BB. Why neighbors suffice: if uu occurs in AA at ii and in BB at jj, between rows of TiT_i and TjT_j suffix origin changes from AA to BB at some neighboring pair, which shares at least ∣u∣\abs{u} characters by the minimum theorem. Separator #\texttt{\#} guarantees no common prefix extends from AA to BB. With A=bananaA = \texttt{banana} and B=ananasB = \texttt{ananas}, 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.

InteractiveThe LCP landscape
0100200300400suffixes in suffix-array order (r = 0 … 1955)
  • lcp[r]: common prefix with preceding suffix
  • above threshold
Row r=537r = 537: lcp[537]=402\mathrm{lcp}[537] = 402. Neighboring suffixes at text positions 574 and 106.
574 ·y·devuelve·una·lista·de·ejemplos."""↵····examples·=·[]↵····with·open(path,·encoding="utf-8")·as …(+306) build_vocab(ex
106 ·y·devuelve·una·lista·de·ejemplos."""↵····examples·=·[]↵····with·open(path,·encoding="utf-8")·as …(+306) load_valid(pat
Longest repeats (tap one to inspect)
Text: pale orange marks positions inside a repeat ≥ threshold; blue marks the two occurrences in the selected row
import json
import numpy as np


def load_train(path, max_len=512):
    """Lee el fichero de entrenamiento y devuelve una lista de ejemplos."""
    examples = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            record = json.loads(line)
            text = record["text"].strip()
            if not text:
                continue
            tokens = text.split()[:max_len]
            examples.append({"tokens": tokens, "label": int(record["label"])})
    return examples


def load_valid(path, max_len=512):
    """Lee el fichero de validación y devuelve una lista de ejemplos."""
    examples = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            record = json.loads(line)
            text = record["text"].strip()
            if not text:
                continue
            tokens = text.split()[:max_len]
            examples.append({"tokens": tokens, "label": int(record["label"])})
    return examples


def build_vocab(examples, min_count=2):
    counts = {}
    for ex in examples:
        for tok in ex["tokens"]:
            counts[tok] = counts.get(tok, 0) + 1
    vocab = {"<pad>": 0, "<unk>": 1}
    for tok, c in sorted(counts.items()):
        if c >= min_count:
            vocab[tok] = len(vocab)
    return vocab


def encode(examples, vocab, max_len=512):
    ids = np.zeros((len(examples), max_len), dtype=np.int64)
    for i, ex in enumerate(examples):
        for j, tok in enumerate(ex["tokens"][:max_len]):
            ids[i, j] = vocab.get(tok, vocab["<unk>"])
    return ids


def accuracy(pred, gold):
    pred = np.asarray(pred)
    gold = np.asarray(gold)
    return float((pred == gold).mean())


if __name__ == "__main__":
    train = load_train("data/train.jsonl")
    valid = load_valid("data/valid.jsonl")
    vocab = build_vocab(train)
    x_train = encode(train, vocab)
    x_valid = encode(valid, vocab)
    print(len(vocab), x_train.shape, x_valid.shape)
40 characters
Characters mm (without sentinel)1 955
Longest repeat (max LCP)402 characters
Distinct substrings m(m+1)2−∑lcp\tfrac{m(m+1)}{2} - \sum \mathrm{lcp}1 823 554
Runs with lcp ≥ 40370
Text inside repeats ≥ threshold45.8 %
The LCP array of real text, with suffixes in suffix-array order. Start with a Python module of about 2000 characters. The forest of high peaks is one repetition: the bodies of 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 hh is a fragment of hh characters appearing at least twice, and a plateau of width ww above a threshold is a fragment appearing w+1w + 1 times. One copy of length hh leaves a characteristic signature: peaks of heights h,h−1,h−2,…h, h - 1, h - 2, \dots, 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 TiT_i, TjT_j with ti−1≠tj−1t_{i-1} \ne t_{j-1}. 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 m(m+1)/2m(m+1)/2.

The suffix tree

If all suffixes of TT are inserted in a trie, every substring corresponds to a root path, and searching PP costs O(m)\bigO(m). But that trie has Θ(n2)\Theta(n^2) 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 n−1n - 1 internal nodes. Each label is substring T[a,b)T[a, b), stored with two integers, so the tree occupies O(n)\bigO(n) 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 O(n)\bigO(n) with a stack. Traverse rows in order, maintain the tree’s rightmost branch on the stack (nodes of increasing depth), and on reaching row rr close all nodes deeper than lcp[r]\mathrm{lcp}[r] and attach the new leaf to a node of depth exactly lcp[r]\mathrm{lcp}[r], 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.

InteractiveThe suffix tree drawn over the suffix array
024681012depth$imississippi$ps$ppi$ssippi$ssippi$i$pi$ppi$ssippi$isippi$ssippi$rSA[r]lcp[r]011110027134141450069078186093210511123
  • pattern path and SA interval
  • common ancestor of two neighboring leaves (lcp)
The path for “ssi” ends at a node of depth 3; its 2 leaves are rows [10,12)[10, 12) of the suffix array: positions 5, 2. Leaves 3 and 4 separate at depth 4: they share “issi”, so lcp[4]=4\mathrm{lcp}[4] = 4.
Text and pattern
Leaves (suffixes)12
Internal nodes (at most n−1n - 1)7
Interval of “ssi” in the SA[10, 12)
Occurrences2
lcp[4] = depth of common ancestor4 = 4
The suffix tree of 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 t0⋯tkt_0 \cdots t_k has the (implicit, sentinel-free) suffix tree of that prefix. Reading a new character requires extending all current suffixes, naively O(k)\bigO(k) 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 cXcX to that labeled XX) 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 O(n)\bigO(n) 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.

[ ]Brute-force sorted suffixes: the referenceBrowser
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 n=3×109n = 3\times 10^9, keys would occupy about 4.5×10184.5\times 10^{18} bytes. Now prefix doubling from scratch in pure Python, with explicit counting sort so each round visibly compares no characters.

[ ]Prefix doubling from scratchBrowser
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 2log⁡2n2\log_2 n positions, while both periodic texts reach ⌈log⁡2n⌉=12\lceil \log_2 n \rceil = 12: the longest repeat determines round count. Next, Kasai with a comparison counter to check bound 3n3n, and any two suffixes’ LCP using a sparse table.

[ ]Kasai, the 3n bound and arbitrary-pair LCPBrowser
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 nn failures (one per iteration) and nn matches, because overall hh rises as much as it falls and falls at most 1 per iteration. Even in a4095\texttt{a}^{4095}, 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 (rankL[i],rankL[i+L])(\mathrm{rank}_L[i], \mathrm{rank}_L[i + L]), with both components in [−1,n)[-1, n), is packed into integer rankL[i] (n+1)+rankL[i+L]+1\mathrm{rank}_L[i]\,(n + 1) + \mathrm{rank}_L[i + L] + 1: a two-digit base-n+1n + 1 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.

[ ]Suffix index of a dozen standard-library modulesBrowser
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 ⌈log⁡2(558+1)⌉\lceil \log_2(558 + 1) \rceil 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 nn 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, L[r]L[r] is the character preceding the suffix of row rr. For banana$, with SA=[6,5,3,1,0,4,2]\mathrm{SA} = [6, 5, 3, 1, 0, 4, 2], BWT is annb$aa (characters at positions 5,4,2,0,−1,3,15, 4, 2, 0, -1, 3, 1), and F=F = $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 TT: 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 nn times the text’s order-kk empirical entropy (in a slightly modified variant, Hk∗H_k^*), plus lower-order terms, for all kk simultaneously and without knowing kk: 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 cc, shifted so cc moves to the front, retain their relative order because they all now start with the same cc and the remainder preserves its order. You will prove it step by step in an exercise. In SA\mathrm{SA}, LF is simply rank[SA[r]−1]\mathrm{rank}[\mathrm{SA}[r] - 1]: it moves one text position backward. But it is calculated without SA, using CC and rank\mathrm{rank} on LL.

LF reconstructs text right to left. Row 0 is the rotation starting with $\texttt{\textdollar}, so its LL is tn−2t_{n-2}, the last character before the sentinel. Applying LF goes back one position: L[LF(0)]=tn−3L[\mathrm{LF}(0)] = t_{n-3}, and so on. In banana$: row 0 yields a; LF(0)=C[a]+0=1\mathrm{LF}(0) = C[\texttt{a}] + 0 = 1 yields n; LF(1)=C[n]+0=5\mathrm{LF}(1) = C[\texttt{n}] + 0 = 5 yields a; in total read a, n, a, n, a, b: text backwards. There are n−1n - 1 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 [sp,ep)[sp, ep) are rotations starting with QQ, those starting with cQcQ are LF images of interval rows whose LL is cc, and by LF correspondence those images are consecutive.

Proof

A rotation starts with cQcQ if and only if it is the LF image of a row starting with QQ and ending in cc: shifting a rotation moves its last character to the front. Rows of [sp,ep)[sp, ep) with L[r]=cL[r] = c are occurrences of cc in LL with occurrence index between rankc(L,sp)\mathrm{rank}_c(L, sp) (inclusive) and rankc(L,ep)\mathrm{rank}_c(L, ep) (exclusive). By LF correspondence, the kk-th cc of LL moves to row C[c]+kC[c] + k. Their images are therefore rows C[c]+kC[c] + k with kk in that range, the stated interval. If no cc exists in [sp,ep)[sp, ep), the endpoints coincide and the interval is empty.

∎

Watch the search for abra in abracadabra$. Text is never needed: toggle it on and off.

InteractiveBackward search in the FM-index
Patternabra
rSAFLFLF0·$abracadabra$01·a$abracadabra12·abra$abracada230abracadabra$a34·acadabra$abra45·adabra$abraca568bra$abracadab67·bracadabra$ab784cadabra$abrac89·dabra$abracad910·ra$abracadabr1011·racadabra$abr11
CC table (characters less than cc):$ : 0a : 1b : 6c : 8d : 9r : 10
[sp,ep)=[0,12)[sp, ep) = [0, 12)
  • interval [sp, ep)
  • c in L (interval entries marked)
  • row with sampled SA
step 1 / 10
Empty pattern: the interval is [sp,ep)=[0,12)[sp, ep) = [0, 12), all rows. The index stores only column LL (the BWT), table CC and a sample of the suffix array. We will read «abra» from right to left.
Text and pattern
SA sampling: one position per
Interval [sp,ep)[sp, ep)[0, 12)
Occurrences ep−spep - sp12
Rank queries0
Text characters read0
The sorted rotation matrix of abracadabra$, with column FF, a faded center and column LL (the BWT, ard$rcaaaabb). At right, FF 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 [0,12)[0, 12) to [1,6)[1, 6); then r: LL has two rs inside the interval and none above, so rows jump to [C[r]+0,C[r]+2)=[10,12)[C[\texttt{r}] + 0, C[\texttt{r}] + 2) = [10, 12); then b gives [6,8)[6, 8) and finally a gives [2,4)[2, 4): two occurrences. Enable ‘Hide what is not stored’: search uses only LL and CC. 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 rankc(L,i)\mathrm{rank}_c(L, i). Counting by scanning LL would cost O(n)\bigO(n) per query. The standard solution is checkpoints: every bb positions, store for each character how many occurrences appeared so far. A query takes the checkpoint preceding ii and counts within at most bb characters. With σ\sigma characters and 32-bit counters, checkpoints occupy 32σn/b32\sigma n/b bits. For DNA (σ=4\sigma = 4 plus sentinel) with b=64b = 64 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 O(log⁡σ)\bigO(\log \sigma) with nlog⁡σn\log\sigma bits plus lower-order terms.

Locate: sample the suffix array

Backward search counts but does not say where. For that, store SA[r]\mathrm{SA}[r] only in rows whose value is a multiple of ss, namely text positions 0,s,2s,…0, s, 2s, \dots. To locate row rr, apply LF until reaching a sampled row: after kk steps the position is SA[r]−k\mathrm{SA}[r] - k, and if its stored value is vv the answer is v+kv + k. Since samples are every ss text positions, at most s−1s - 1 steps suffice. To determine whether a row is sampled and where its value lies in the sample, use an nn-bit vector marking those rows, with rank support. The sample uses (n/s)log⁡2n(n/s)\log_2 n bits: with s=32s = 32 and 32-bit integers, one bit per character, and the marker vector another bit per character.

For a human genome of 3.1×1093.1\times 10^9 bases: BWT packed at 2 bits per base occupies about 775 MB; checkpoints with b=64b = 64 another 775 MB; samples with s=32s = 32 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 O(nHk(T))\bigO(n H_k(T)) bits plus lower-order terms, where HkH_k is empirical entropy of order kk; later wavelet-tree versions reduce this to nHk(T)+o(nlog⁡σ)n H_k(T) + o(n \log\sigma). 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 LL.

[ ]BWT from the suffix array and LF inversionBrowser
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.

[ ]FM-index with block rank and sampled SABrowser
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 (s−1)/2=15.5(s - 1)/2 = 15.5, 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 b=64b = 64 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 4⋅106/64≈6.64 \cdot 106 / 64 \approx 6.6 bytes per position. This motivates wavelet trees for text and bit blocks for DNA, where σ=4\sigma = 4. Finally, verify BWT does not compress on its own.

[ ]BWT does not compress: MTF, entropy and bz2Browser
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

NeedTool
Build SA (and LCP) of bytes or integerslibsais (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 readsBWA, Bowtie 2 (genome FM-index)
Deduplicate a text corpusdeduplicate-text-datasets (Lee and colleagues, Rust, with suffix arrays)
Count arbitrary-length nn-gramsinfini-gram (suffix arrays over tokens)
Block compressionbz2 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 nn-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

NumericDistinct substrings of banana
Calculate by hand the suffix array and LCP array of banana$\texttt{banana\textdollar} and use them to find the number of distinct nonempty substrings of banana\texttt{banana} (without the sentinel).
QuizThe BWT of banana$
What is the Burrows-Wheeler transform of banana$\texttt{banana\textdollar}, with $\texttt{\textdollar} smaller than letters?
NumericWorst-case doubling rounds
How many doubling rounds (after round 0, which sorts by first character) does prefix doubling need for text a15$\texttt{a}^{15}\texttt{\textdollar} of 16 characters?
NumericInternal suffix-tree nodes
Text panamabananas$\texttt{panamabananas\textdollar} (n=14n = 14) has SA=[13,5,3,1,7,9,11,6,4,2,8,10,0,12]\mathrm{SA} = [13, 5, 3, 1, 7, 9, 11, 6, 4, 2, 8, 10, 0, 12] and LCP array [0,0,1,1,3,3,1,0,0,0,2,2,0,0][0, 0, 1, 1, 3, 3, 1, 0, 0, 0, 2, 2, 0, 0]. How many internal nodes, counting the root, does its suffix tree have?
NumericA genome's SA sample
An FM-index of the human genome (n=3.1×109n = 3.1\times 10^9) stores the suffix array only at text positions divisible by s=32s = 32, using 4-byte integers. How many MB (of 10610^6 bytes) does the sample occupy?
QuizWhich structure for each job?
Three jobs: (A) locate hundreds of millions of short reads in the human genome, with arbitrary patterns and a 16 GB machine; (B) scan network traffic in real time for 10,000 fixed signatures known in advance; (C) find all fragments of at least 50 tokens repeated in a pretraining corpus. Which combination is most sensible?
ProofKasai's lemma and linear cost
Prove: For every position ii with rank[i]>0\mathrm{rank}[i] > 0 and i+1<ni + 1 < n, lcp[rank[i+1]]≥lcp[rank[i]]−1\mathrm{lcp}[\mathrm{rank}[i+1]] \ge \mathrm{lcp}[\mathrm{rank}[i]] - 1. Consequently Kasai's algorithm makes O(n)\bigO(n) comparisons.
0
Let h=lcp[rank[i]]h = \mathrm{lcp}[\mathrm{rank}[i]]. If h≤1h \le 1, the inequality is trivial (lcp≥0≥h−1\mathrm{lcp} \ge 0 \ge h - 1). Suppose h≥2h \ge 2 and let j=SA[rank[i]−1]j = \mathrm{SA}[\mathrm{rank}[i] - 1] be the position of the suffix preceding TiT_i in the array.

Step 1 of 5. What do you know about TjT_j versus TiT_i?

ProofLF inverts BWT
Prove: Let r1<r2r_1 < r_2 be two rows of the sorted rotation matrix with L[r1]=L[r2]=cL[r_1] = L[r_2] = c. Their shifted rotations (with cc in front) lie in rows LF(r1)<LF(r2)\mathrm{LF}(r_1) < \mathrm{LF}(r_2). Thus the kk-th cc of LL is the kk-th cc of FF, LF(r)=C[c]+rankc(L,r)\mathrm{LF}(r) = C[c] + \mathrm{rank}_c(L, r), and applying LF from row 0 reconstructs the text.
0
Call the rotation in row rr RrR_r and write Rr=Xr cR_r = X_r\,c, where XrX_r is its first n−1n - 1 characters. The shifted rotation is c Xrc\,X_r.

Step 1 of 4. Why does Rr1<Rr2R_{r_1} < R_{r_2} imply Xr1<Xr2X_{r_1} < X_{r_2}?

CodeDistinct substrings with SA and LCP
Implement 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) // 2
Shift+Enter to run

Summary

Key idea
Every substring prefixes a suffix: sorting suffixes once turns any search into binary search and any repetition into an LCP-array peak; BWT, that same order read one character to the left, enables searching without storing the text or full order.
  • The suffix array is the permutation sorting suffixes of T$T\texttt{\textdollar}; pattern occurrences form a row interval found by two binary searches in O(mlog⁡n)\bigO(m\log n), or O(m+log⁡n)\bigO(m + \log n) with LCP information.
  • Prefix doubling sorts by the first 1,2,4,…1, 2, 4, \dots characters using rank pairs and radix sort: ⌈log⁡2(ℓmax⁡+1)⌉\lceil\log_2(\ell_{\max} + 1)\rceil rounds of O(n)\bigO(n). SA-IS does it in O(n)\bigO(n) with induced sorting.
  • The LCP array stores neighbors’ common prefix; an arbitrary pair’s LCP is a range minimum (RMQ). Kasai computes it in O(n)\bigO(n) by traversing in text order, because LCP falls by at most 1 from one suffix to the next.
  • Longest repetition, distinct substrings (m(m+1)/2−∑lcpm(m+1)/2 - \sum\mathrm{lcp}) and longest common substring of two texts are solved with one LCP pass.
  • The suffix tree is the compact trie of suffixes, with O(n)\bigO(n) 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, L[r]=tSA[r]−1L[r] = t_{\mathrm{SA}[r]-1}. 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 LF(r)=C[c]+rankc(L,r)\mathrm{LF}(r) = C[c] + \mathrm{rank}_c(L, r).
  • The FM-index counts occurrences of PP with 2m2m rank queries (backward search), locates using LF to an SA sampled every ss 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.