AlgoViz

Burrows–Wheeler transform

hard 12 min

Sort every rotation of a marked string and keep the last column.

Video lesson · Chapter 1 of 10

A scrambled parcel arrives

0:00 / 3:38

The Burrows–Wheeler transform in 90 seconds

1:27Reel

Theory

Read or listen first. About 1 min.

What it is

A cyclic rotation moves a prefix of a string to its end. The Burrows–Wheeler transform sorts the rotations of a block and records the character immediately before the start of each sorted rotation.

This lesson uses uppercase letters and one end marker, $, which sorts first. The marker makes every rotation distinct and identifies the original row. A version that omits the marker carries the original row number alongside the result.

Why it exists

Rotations with the same beginning sit together. If similar text contexts often have the same preceding letter, the output contains groups of repeated symbols that a later encoder can exploit.

The set of characters and the length of the marked block stay the same. The saving, when there is one, comes from how a subsequent stage represents the rearranged symbols.

A short history

  1. 1994

    Michael Burrows and David Wheeler published a block-sorting compression method that transforms a block before encoding it.

Words to know

End marker
A single reserved symbol that identifies the block boundary.
Occurrence rank
A letter’s position among copies of that same letter when reading a column from top to bottom.
LF mapping
A link from a row’s last-column letter to the same ranked letter in the first column. Following it steps one position backward in the original text.

How it works

Step through the idea, or press Play.

Step 1 of 3

Rotate the marked block. BANANA$ has seven positions and seven rotations. Each letter at the end of a row precedes the letter at its beginning on the circular block.

Understand it

Encode

Seven rotations, one output column

Imagine writing BANANA$ on a paper ring. Keep the ring still and move a reading window one position at a time. Reading all seven characters at each start gives the rows below. The original block starts at position zero.

Sorted rowStart in BANANA$RotationLast
06$BANANAA
15A$BANANN
23ANA$BANN
31ANANA$BB
40BANANA$$
54NA$BANAA
62NANA$BAA
Read down the last column to obtain ANNBAA.ThefirstcolumnreadsAA. The first column reads AAABNN.

Decode

Give each repeated letter an address

Read the last column top to bottom and number copies of each letter starting at one. Do the same in the first column. The second N in the last column must match the second N in the first. Moving that N to the front preserves the relative order of the following text, so the occurrence ranks agree.

RowLast with rankFirst with rankLF target row
0A₁$₁1
1N₁A₁5
2N₂A₂6
3B₁A₃4
4$₁B₁0
5A₂N₁2
6A₃N₂3
To find a target, take the ranked entry in Last and locate exactly that entry in First. Row numbers start at zero.

Try the inverse

Start at the row ending in the marker

Find $ in the last column, at row 4. Read it, then jump to row 0, where the first column contains $. Row 0 emits A₁ and jumps to row 1. Which letter comes next? Row 1 emits N₁ and jumps to row 5.

Visited rowsLast-column symbols emittedResult
4 → 0 → 1 → 5 → 2 → 6 → 3$ A N A N A B$ANANAB
Reverse the emitted symbolsB A N A N A $BANANA$
Each LF jump walks backward on the ring. After seven emits, reversing the sequence restores the original marked block.

Implement

Count previous copies to build each link

In zero-based code the LF target is the first index of the character in the sorted column plus the number of earlier copies in the last column. For N₂ at row 2, N starts at row 5 and there is one earlier N, so the target is row 6.

Python
def transform(text):    # The teaching alphabet is uppercase A–Z. The unique $ sorts before A.    if any(ch < "A" or ch > "Z" for ch in text):        raise ValueError("use uppercase A-Z")    marked = text + "$"    rows = sorted(marked[i:] + marked[:i] for i in range(len(marked)))    return "".join(row[-1] for row in rows)def invert(last):    # Input is the transform of an uppercase block with one end marker.    if last.count("$") != 1:        raise ValueError("expected one end marker")    first = sorted(last)    start = {}    for row, ch in enumerate(first):        start.setdefault(ch, row)    seen = {}    lf = []    for ch in last:        earlier = seen.get(ch, 0)        lf.append(start[ch] + earlier)        seen[ch] = earlier + 1    row = last.index("$")    backwards = []    for _ in last:        backwards.append(last[row])        row = lf[row]    return "".join(reversed(backwards))encoded = transform("BANANA")print(encoded)          # ANNB$AAprint(invert(encoded))  # BANANA$
The forward example explicitly builds the matrix for clarity. The inverse uses two columns and one row link per symbol.
Edit and run it in your browser

Let n include the marker. Building n strings of length n consumes quadratic space. Comparing the complete rotations during sorting can take O(n² log n) time. In production, a suffix array can supply the sorted starting offsets without building the matrix. The decoder here spends O(n log n) time sorting this column and O(n) extra space. For a fixed alphabet, counting symbol frequencies gives the first-column offsets in linear time.

Summary

The whole topic in one minute.

Sorting the seven rotations of BANANAandtakingtheirlastlettersgivesANNB and taking their last letters gives ANNBAA.

Sorting that column recovers First. Pairing equal letters by rank supplies the backward links that recover BANANA$.

Sources