Suffix Arrays
A suffix array lists the start of every suffix of a text, sorted by the suffix itself. It is one integer per character, yet with binary search and an LCP array beside it, it finds patterns, counts occurrences and finds repeats.
Sorted Suffixes, Stored as Integers
A suffix array is an array of the starting positions of every suffix of a string, sorted by the lexicographic order of the suffixes themselves. For a text of length n, it holds n integers and nothing else.
The critical point is that the suffixes are not stored. Storing them would need O(n²) characters, since the suffixes of a length-n string total n(n+1)/2 characters. Only their starting positions are kept, and the original text is retained alongside — any suffix is then recoverable as a slice from its position to the end.
For the text banana, the suffixes sorted lexicographically are a, ana, anana, banana, na, nana, whose starting positions are 5, 3, 1, 0, 4, 2. That list of six integers is the suffix array.
The reason this is useful rests on one observation, the same one that motivates suffix trees: every substring of the text is a prefix of some suffix. So questions about substrings become questions about prefixes of the sorted suffix list — and a sorted list can be binary searched.
Space is the headline advantage. The array costs 4 bytes per character with 32-bit integers, or 8 with 64-bit, while a suffix tree typically needs 10 to 20 bytes per character. That is about three to five times less memory, and it is one contiguous block instead of scattered nodes, so scanning it is cache-friendly in a way pointer-chasing is not.
This is why suffix arrays replaced suffix trees in most practical tools, even though the tree has the better search bound. At the sizes where these structures are used, memory and cache behaviour matter more than the extra log factor.
- With a
$sentinel appended, the suffix$sorts first:banana$gives [6, 5, 3, 1, 0, 4, 2] - The inverse array,
rank[SA[i]] = i, says where each suffix landed; Kasai's algorithm needs it - Texts longer than 2³¹ characters need 64-bit entries, which doubles the memory
Searching by Binary Search
Because the suffixes are in sorted order, all suffixes beginning with a given pattern occupy a contiguous block of the array. Finding a pattern means locating that block.
A standard binary search does it. At each step, compare the pattern against the suffix at the midpoint position — a comparison costing up to O(m) for a pattern of length m — and narrow the range accordingly. With O(log n) steps, a search costs O(m log n).
Using lower bound and upper bound searches finds the block's two edges, and every position between them is an occurrence. The count of occurrences is the difference of the two bounds, available in O(1) once the block is located, and the positions themselves are read directly from the array.
Compare the alternatives. A suffix tree searches in O(m), independent of n, which is asymptotically better (the full comparison is on the suffix trees lesson). KMP scans the text in O(n + m) for every pattern, which is worse whenever a large text is searched many times.
So the suffix array sits between them: it gives up the tree's O(m) for an extra log factor and is a fraction of the size. For a one-gigabyte text, log₂ n is about 30, a modest multiplier for a several-fold memory saving.
That log factor can be removed. Augmenting the array with the LCP information described next allows the comparisons to skip characters already known to match, bringing the search to O(m + log n). With that refinement the practical gap to a suffix tree largely disappears, which is the final reason suffix arrays win in production.
- The empty pattern matches all n rows; a pattern longer than every suffix matches none
- Comparisons stop after m characters: a row that merely starts with the pattern counts as equal
- Practice: number of distinct substrings, repeated DNA sequences, first occurrence in a string
The LCP Array
The LCP array (longest common prefix) stores, for each row i of the suffix array, the length of the longest prefix shared by the suffix in row i and the suffix in row i − 1. It is n more integers, and it lets a sorted list answer most of the questions a suffix tree answers.
For banana, the sorted suffixes a, ana, anana, banana, na, nana share prefixes of length 0, 1, 3, 0, 0, 2 with their predecessors. Note the value 3 between ana and anana — adjacent suffixes in sorted order tend to share long prefixes, which is exactly the information being captured.
Kasai's algorithm computes the whole LCP array in O(n) from the suffix array and its inverse. It visits suffixes in text order rather than sorted order, because if the suffix starting at i shares h characters with its sorted neighbour, the suffix starting at i + 1 shares at least h − 1 with its own. The count never has to restart from zero, it drops by at most 1 per step, so the total character comparisons stay below 2n.
What the array enables is the important part. The longest repeated substring is the maximum value in the LCP array. A substring that occurs twice is a shared prefix of two suffixes, and the longest shared prefix of any two suffixes is always found between two that are adjacent in sorted order. One pass over the array answers it.
The number of distinct substrings is n(n+1)/2 − sum(LCP). The n(n+1)/2 suffix prefixes list every substring with repeats, and each LCP value counts exactly the prefixes a suffix repeats from its neighbour. For banana: 21 − 6 = 15.
The longest common substring of two texts is found by concatenating them with a separator, building the suffix array, and taking the maximum LCP value between adjacent suffixes originating from different texts.
Combined with a sparse table for range minimum queries over the LCP array, the shared prefix of any two suffixes is answered in O(1): it is the minimum LCP between their rows.
- LCP[0] has no row above; store 0 or leave it undefined
- Longest common substring of
ababandbaba: build onabab#babaand take the largest LCP between rows from different texts (3:abaorbab) - Adjacent LCP values are not the shared prefix of rows far apart; that needs the minimum over the range between them
Terms, operations, and practical uses
Fundamentals
- Suffix ArrayAn array of integers representing the starting indices of all suffixes of a string, sorted in lexicographical order.
- Memory ProfileRequires exactly O(N) integers to store, making it vastly more practical than generating all string copies.
- Substring PropertyEvery single substring of the text is simply a prefix of one of the suffixes in the suffix array.
Operations
- Pattern MatchingBecause the suffixes are sorted, finding a pattern of length M in text of length N takes O(M log N) via Binary Search.
- LCP ArrayThe Longest Common Prefix array stores the length of the matching prefix between adjacent suffixes in the sorted Suffix Array.
- Repeated SubstringsThe maximum value in the LCP array is the length of the longest substring that appears at least twice in the text.
Construction
- Naive SortExtracting all suffixes and running QuickSort takes O(N² log N) due to string comparison overhead.
- Prefix DoublingSorts prefixes of length 1, then 2, 4, 8, etc., updating a rank array. Constructs the Suffix Array in O(N log² N).
- DC3 / SA-ISAdvanced algorithms capable of constructing the Suffix Array in strictly O(N) linear time.
Code in Python, C++ and Java
def build_suffix_array(s):
suffixes = [(s[i:], i) for i in range(len(s))]
suffixes.sort()
return [idx for suffix, idx in suffixes]
print('SA:', build_suffix_array('banana'))#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
vector<int> buildSuffixArray(string s) {
vector<pair<string, int>> suffixes;
for (int i = 0; i < s.length(); i++)
suffixes.push_back({s.substr(i), i});
sort(suffixes.begin(), suffixes.end());
vector<int> sa;
for (auto& p : suffixes) sa.push_back(p.second);
return sa;
}
int main() {
vector<int> sa = buildSuffixArray("banana");
cout << "SA: [";
for(size_t i = 0; i < sa.size(); i++) {
if (i) cout << ", ";
cout << sa[i];
}
cout << "]\n";
}import java.util.*;
public class Main {
public int[] build(String s) {
String[] suffixes = new String[s.length()];
Integer[] indices = new Integer[s.length()];
for (int i = 0; i < s.length(); i++) {
suffixes[i] = s.substring(i);
indices[i] = i;
}
Arrays.sort(indices, (a, b) -> suffixes[a].compareTo(suffixes[b]));
return Arrays.stream(indices).mapToInt(i->i).toArray();
}
public static void main(String[] args) {
System.out.println("SA: " + Arrays.toString(new Main().build("banana")));
}
}Step through it
Running on text "banana", search "ana" and "nab"
Three Ways to Build It
Suffix array construction is where the algorithmic work sits, and three approaches are worth knowing.
Naive sorting generates all n suffixes and sorts them with a standard comparison sort. Each comparison costs up to O(n), so the total is O(n² log n) — and it also needs O(n²) memory if the suffixes are materialised. Unusable beyond small inputs, but worth stating as the baseline the others improve on.
Prefix doubling, the Manber–Myers approach, is the practical method to know. It sorts the suffixes by their first character, then their first 2 characters, then 4, 8, and so on, doubling each round. The key trick is that after sorting by the first k characters, each suffix can be given a rank, and sorting by the first 2k characters requires only comparing pairs of ranks — an O(1) comparison rather than an O(k) one, because the ranks already encode the first k characters.
With log n doubling rounds and an O(n log n) sort in each, the total is O(n log² n); replacing the comparison sort with radix sort on the rank pairs gives O(n log n). This is the algorithm most competitive programmers implement, because it is short and fast enough for essentially any input size.
Linear-time construction exists. The DC3 / skew algorithm and SA-IS both run in O(n). Induced-sorting methods (SA-IS and the closely related libdivsufsort) are what fast libraries use, because they are quick in practice as well as in theory. Both are much harder to write than prefix doubling, which is the usual reason to use a library.
For interview purposes, the expected answer is usually to describe prefix doubling and to know that O(n) construction exists. For production use, the answer is to use an existing implementation — sais, the SDSL library, or the language's equivalent.
Where suffix arrays are used: bioinformatics indexes a reference genome once and looks up billions of short reads in it. Data compression uses the closely related Burrows–Wheeler transform, which can be read straight off the suffix array (each row's preceding character) and underlies bzip2. Full-text search uses suffix arrays or the FM-index, a compressed form that stays searchable, and is the direction the field has moved.
- Prefix doubling on
bananasorts by 1, 2, then 4 characters; after the 4-character round all ranks differ, so it stops early - The naive build in the code above is O(n² log n) but fine for a few thousand characters
- bzip2 sorts blocks of 100 to 900 kB, small enough that construction speed per block matters more than asymptotics