8. Suffix Arrays

Sort every suffix, then answer substring queries in logarithmic time

You have a 3-billion-character genome and you need to find every place a short sequence appears. Or you're building a full-text search engine and need instant substring lookup across millions of documents. Scanning from the beginning each time is far too slow.

The suffix array solves this by precomputing a sorted index of every suffix in the text. Once built, finding any substring takes just O(m log n) time — where m is the pattern length and n is the text length — no matter how large the text is.

What Is a Suffix?

A suffix of a string is everything from some position to the end. The string "banana" has six suffixes — one starting at each character:

All suffixes of "banana"

Index   Suffix
  0     banana
  1     anana
  2     nana
  3     ana
  4     na
  5     a

Every substring of a string is a prefix of one of its suffixes. This is the key insight that makes suffix-based data structures so powerful: if you can efficiently search over all suffixes, you can find any substring.

The Suffix Array

A suffix array is simply the array of starting indices of all suffixes, sorted in alphabetical order. Instead of storing the full suffix strings (which would take O(n²) space), we store just the indices — the original text is always available for comparison.

Core Idea

Sort all suffixes alphabetically, but only store their starting positions. The sorted order lets you binary search for any pattern, just like searching a dictionary.

Worked Example: Building the Suffix Array for "banana$"

We append a sentinel character $ that is lexicographically smaller than any other character. This guarantees that no suffix is a prefix of another, which simplifies sorting and searching.

Step 1 — List all suffixes

Index   Suffix
  0     banana$
  1     anana$
  2     nana$
  3     ana$
  4     na$
  5     a$
  6     $

Step 2 — Sort alphabetically

Sorted    Index   Suffix
  0         6     $
  1         5     a$
  2         3     ana$
  3         1     anana$
  4         0     banana$
  5         2     nana$
  6         4     na$

The suffix array is: SA = [6, 5, 3, 1, 0, 2, 4]

That's it. The suffix array is just those indices: [6, 5, 3, 1, 0, 2, 4]. It takes exactly O(n) space (one integer per character) — far less than storing a suffix tree.

Searching for a Substring

Because the suffixes are sorted, we can binary search for any pattern, just like looking up a word in a dictionary. To find the pattern "ana" in "banana$":

  1. Start binary search on the suffix array

    Compare "ana" with the suffix at the midpoint of the array. The midpoint of SA = [6, 5, 3, 1, 0, 2, 4] is index 3, which is SA[3] = 1, meaning suffix "anana$".

  2. Compare the pattern against the suffix prefix

    We compare only the first m = 3 characters: "ana" vs "ana" — it's a match!

  3. Expand to find all occurrences

    Since there may be multiple matches, scan left and right from the hit. SA[2] = 3 gives suffix "ana$" — also starts with "ana". SA[4] = 0 gives "banana$" — does not start with "ana". Stop.

  4. Result

    Pattern "ana" occurs at positions 1 and 3 in the original string.

Search Complexity

Each binary search step compares m characters, and there are O(log n) steps, giving O(m log n) total time. With the LCP array (below), this can be improved to O(m + log n).

The LCP Array

The Longest Common Prefix (LCP) array is a companion structure that stores, for each pair of adjacent suffixes in the sorted order, how many leading characters they share.

LCP array for "banana$"

Rank  SA[i]  Suffix      LCP[i]
  0     6    $             —
  1     5    a$            0
  2     3    ana$          1
  3     1    anana$        3
  4     0    banana$       0
  5     2    nana$         0
  6     4    na$           2

LCP[3] = 3 because "ana$" and "anana$" share the prefix "ana". LCP[6] = 2 because "nana$" and "na$" share "na".

The LCP array is invaluable for several reasons:

  • Faster search: During binary search, the LCP values tell you how much of the pattern you've already matched, avoiding redundant comparisons — improving search to O(m + log n)
  • Counting distinct substrings: The total number of distinct substrings equals n(n+1)/2 minus the sum of LCP values
  • Longest repeated substring: Simply the maximum value in the LCP array

The LCP array can be built in O(n) time using Kasai's algorithm, which exploits the fact that if two suffixes share a long prefix, removing the first character leaves suffixes that share a prefix at most one shorter.

Naive Construction

The simplest way to build a suffix array is to just sort all the suffixes:

function buildSuffixArray(text):
    n = length(text)
    suffixes = [(text[i..n], i) for i in 0..n-1]
    sort suffixes alphabetically
    return [index for (_, index) in suffixes]

Sorting n suffixes takes O(n log n) comparisons, and each comparison examines up to O(n) characters, giving a total of O(n² log n). For small strings this is fine, but for a genome with billions of characters, we need something faster.

Efficient Construction

Algorithms like SA-IS (Suffix Array by Induced Sorting) build the suffix array in O(n) time. The prefix-doubling approach achieves O(n log n) by iteratively sorting suffixes by their first 1, 2, 4, 8, ... characters, using the results of the previous round as sort keys.

Connection to the Burrows-Wheeler Transform

The suffix array is intimately linked to the Burrows-Wheeler Transform (BWT), a cornerstone of data compression.

From suffix array to BWT

Given text T = "banana$" and SA = [6, 5, 3, 1, 0, 2, 4]:

BWT[i] = T[SA[i] - 1] (or T[n-1] if SA[i] = 0)

SA[0] = 6 → T[5] = 'a' SA[1] = 5 → T[4] = 'n' SA[2] = 3 → T[2] = 'n' SA[3] = 1 → T[0] = 'b' SA[4] = 0 → T[6] = '$' SA[5] = 2 → T[1] = 'a' SA[6] = 4 → T[3] = 'a'

BWT = "annb$aa"

The BWT groups similar characters together — notice the repeated a's and n's — making the output highly compressible with run-length encoding or move-to-front coding.

Building a suffix array is one of the most efficient ways to compute the BWT, and conversely, the BWT can be used to reconstruct the suffix array. Tools like bzip2 and bioinformatics aligners (BWA, Bowtie) exploit this connection.

Suffix Arrays vs. Suffix Trees

PropertySuffix ArraySuffix Tree
Space O(n) integers — typically 4n-8n bytes O(n) nodes — but 10n-20n bytes with pointers
Construction O(n) with SA-IS, very cache-friendly O(n) with Ukkonen's, but pointer-heavy
Pattern search O(m log n) or O(m + log n) with LCP O(m) — optimal
Cache behavior Excellent — sequential array access Poor — random pointer chasing
Implementation Simple (especially naive version) Complex (Ukkonen's is notoriously tricky)

In practice, suffix arrays with LCP arrays can simulate nearly every suffix tree operation, and they use 3-5x less memory. This is why modern bioinformatics tools and full-text search engines overwhelmingly prefer suffix arrays.

Complexity Summary

Operation Time Notes
Naive construction O(n² log n) Sort all suffixes directly
Prefix doubling O(n log n) Sort by doubling prefix lengths
SA-IS O(n) Linear-time induced sorting
LCP array (Kasai) O(n) Built after the suffix array
Pattern search O(m log n) Binary search; O(m + log n) with LCP
Space O(n) One integer per character

Where Suffix Arrays Are Used

Application How it uses suffix arrays
Bioinformatics Index entire genomes (3+ billion characters) for fast sequence alignment — tools like BWA and Bowtie
Full-text search Build substring indexes for document collections, enabling instant pattern lookup
Data compression Compute the Burrows-Wheeler Transform for bzip2 and similar compressors
Plagiarism detection Find longest common substrings between documents using generalized suffix arrays
Data deduplication Identify repeated byte sequences in storage systems
Competitive programming Solve string problems (repeated substrings, pattern matching, LCP queries) efficiently

Key Takeaways

  • A suffix array is the sorted list of starting indices of all suffixes of a string — it takes O(n) space
  • Because suffixes are sorted, binary search finds any substring in O(m log n) time
  • The LCP array stores how many leading characters adjacent sorted suffixes share, enabling faster search and many string queries
  • Naive construction is O(n² log n), but algorithms like SA-IS achieve O(n)
  • Suffix arrays are closely tied to the Burrows-Wheeler Transform — each can be derived from the other
  • Compared to suffix trees, suffix arrays use far less memory while supporting nearly the same operations
  • They power real-world systems from genome indexing to full-text search to data compression

Suffix arrays are one of those rare data structures where elegance meets practicality. A simple idea — sort the suffixes, keep the indices — unlocks logarithmic-time substring search, connects to the Burrows-Wheeler Transform, and scales to texts with billions of characters. When you need to search a string that doesn't change, the suffix array is one of the best tools in the box.