A suffix array is a deceptively simple idea with outsized power: take every suffix of a string, sort them lexicographically, and store just their starting positions. That sorted order lets you binary-search for any substring in O(m log n), find the longest repeated substring, and much more — all in a compact integer array, a fraction of the memory a suffix tree needs. Pair it with the LCP array — the length of the shared prefix between each pair of neighbours — and repeated patterns fall right out. Sort the suffixes and watch the shared prefixes light up.
O(n log n) construction · O(m log n) substring search · a compact rival to the suffix tree
suffix
The substring from position i to the end. "banana" has 6 suffixes.
suffix array
The starting positions of all suffixes, sorted by the suffixes lexicographically.
LCP array
For each adjacent pair in sorted order, the length of their longest common prefix.
substring search
A pattern occurs iff it is a prefix of some suffix — binary-searchable in the array.
suffix-array.js — sort the suffixes
Ready
The string’s suffixes, sorted lexicographically. Each row shows a suffix, its start index, and the LCP — how many leading characters it shares with the row above. Step to reveal the sorted order.
6
suffixes
0
placed
–
longest repeat
How it works
A suffix array is just an array of integers, yet it answers substring queries almost as well as a full suffix tree. The key observation for search: a pattern P occurs in the text exactly when P is a prefix of at least one suffix. Since the suffixes are sorted, all suffixes starting with P form a contiguous block — so you find them by binary search, in O(m log n). The LCP array adds the other half: the longest common prefix of two adjacent sorted suffixes tells you the longest substring repeated at those two positions, so the maximum LCP value is the length of the longest repeated substring. Naively sorting suffixes is O(n² log n), but classic algorithms build the array in O(n log n) or even O(n).
1
List every suffix
For a string of length n there are n suffixes, one starting at each position. "banana" gives banana, anana, nana, ana, na, a.
2
Sort them lexicographically
Sort the suffixes in dictionary order. The suffix array is the list of their starting positions in this sorted order — a compact integer array.
3
Build the LCP array
For each adjacent pair in the sorted list, record the length of their longest common prefix. The maximum LCP is the longest repeated substring of the text.
✓
Query fast
To find a pattern, binary-search the sorted suffixes: matches form a contiguous block. With the LCP array you also get repeats, distinct substrings, and more — all from one small array.
Build
O(n log n)
Search
O(m log n)
Space
O(n) ints
vs suffix tree
far smaller
The code
# suffix array + LCP (simple O(n^2 log n) build; real ones are O(n log n))def suffix_array(s):
return sorted(range(len(s)), key=lambda i: s[i:]) # sort by suffixdef lcp_array(s, sa):
lcp = [0] * len(sa)
for k in range(1, len(sa)):
a, b = s[sa[k-1]:], s[sa[k]:]
j = 0
while j < len(a) and j < len(b) and a[j] == b[j]: j += 1
lcp[k] = j # shared prefix lengthreturn lcp # max(lcp) = length of the longest repeated substring
Quick check
1. What exactly does a suffix array store?
It stores just the integer starting positions, ordered so that the suffixes they point to are in sorted (dictionary) order. That compactness is its advantage over a suffix tree.
2. How do you search for a pattern using a suffix array?
A pattern P occurs exactly when P is a prefix of some suffix. Because suffixes are sorted, all suffixes starting with P are contiguous, so binary search finds the block in O(m log n).
3. What does the maximum value in the LCP array tell you?
Adjacent sorted suffixes share the longest prefixes, and an LCP of length L between two suffixes means a substring of length L repeats at both positions. So the maximum LCP is the longest repeated substring.
FAQ
What is a suffix array?
An array of the starting positions of all suffixes of a string, sorted so the suffixes are in lexicographic order. It supports fast substring search (binary search) and, with the LCP array, repeated-substring and other queries — using only O(n) integers, far less than a suffix tree.
What is the LCP array?
It stores, for each adjacent pair of sorted suffixes, the length of their longest shared prefix. It supercharges the suffix array: the maximum LCP is the longest repeated substring, and LCP values enable counting distinct substrings and occurrences. Kasai’s algorithm builds it in O(n).
How does a suffix array compare to a suffix tree?
A suffix tree answers more queries optimally but uses much more memory (many pointers) and is fiddly. A suffix array plus LCP array gives most of the same power — search, repeats, distinct substrings — in a compact, cache-friendly integer array. The suffix array is usually preferred in practice.
How fast can a suffix array be built?
Naive string-sorting is O(n² log n). Prefix-doubling (Manber–Myers) is O(n log n), and DC3/skew and SA-IS are O(n). SA-IS is what most high-performance libraries use — linear time and fast in practice.
The picture: sorted suffixes and their LCP
The six suffixes of banana in sorted order, with the start index on the left and the LCP with the row above on the right. Shaded cells are the characters shared with the previous row. A pattern is a prefix of a block of consecutive rows, and the biggest LCP marks the longest repeated substring.
Worked example, step by step
Take S = "banana" (n = 6). The suffix array is the list of start indices after sorting the suffixes as words: [5, 3, 1, 0, 4, 2]. The LCP column compares each suffix with the one above it. Then the last row searches for ana.
Rank
SA[rank]
Suffix
LCP
What it shows
0
5
a
0
smallest suffix
1
3
ana
1
shares “a” with row above
2
1
anana
3
LCP 3 = “ana”, the longest repeat
3
0
banana
0
nothing shared with “anana”
4
4
na
0
starts a new letter
5
2
nana
2
shares “na” with row above
—
—
pattern ana
rows 1–2
found in 5 binary-search steps; occurrences at 1 and 3
The two ana matches sit next to each other, ranks 1 and 2, because sorting puts everything with a common prefix in one block. That block is why a binary search suffices and why the count of occurrences is simply the block’s length, 2. The LCP column carries more: its maximum, 3, is the longest repeated substring (ana), and the number of distinct substrings is n(n+1)/2 − Σ LCP = 21 − 6 = 15. A brute-force set of every substring confirms 15. Building the array by prefix doubling takes only 2 rounds for this string (sorting by the first 2 characters, then the first 4), not one per character.
Complexity and trade-offs
Case
Time
Space
Why
Sort the suffixes directly
O(n² log n) worst case
O(n) indices
Each comparison can scan O(n) characters. On a repeated 250, 500 and 1000 times, one test run of a character-by-character comparator made 31,125, 124,750, 499,500 comparisons: it grows about fourfold per doubling of n.
Prefix doubling with a sort
O(n log² n)
O(n)
At most log₂ n rounds, each a comparison sort of integer pairs.
Prefix doubling with radix sort
O(n log n)
O(n)
Same rounds, each a linear-time bucket sort of pairs.
Linear-time constructions (SA-IS, DC3)
O(n)
O(n)
Optimal, but much harder to write; reach for them when n is in the millions.
Query a built array
O(m log n) per pattern
—
Two binary searches, each step comparing up to m characters; plus the occurrences found.
The array stores n integers, where listing every suffix explicitly would take n(n+1)/2 characters: 500,500 for n = 1,000. A suffix tree answers the same questions in similar time, but its pointers cost several times more memory, which is why the array is the usual choice. If you only ever search one fixed pattern in a text, KMP is simpler and needs no index; the array pays off when the text stays still and the patterns change.
Common mistakes
Sorting suffixes by slicing on repetitive text
sorted(range(n), key=lambda i: s[i:]) is fine for a lesson and a trap for real inputs: it builds every slice, so it uses quadratic memory, and on a string like aaaa…a each comparison scans to the end. At n = 1000 one test run of the character-by-character comparator made 499,500 comparisons. Use prefix doubling or a linear construction.
Reporting only one match
Binary search finds the first suffix with the pattern as a prefix. The matches are the whole block. For ana in banana, taking just the first row gives 3; the occurrences are 1 and 3. Search for both the lower and upper bound.
Taking the LCP of neighbours in the text, not in sorted order
The LCP array compares row k with row k − 1 of the sorted list. Comparing s[i:] with s[i+1:] instead gives [0,0,0,0,0,0] for banana, whose maximum is 0, hiding the repeat ana that the correct LCP array (max 3) finds.
Padding the out-of-range rank with a large number
In prefix doubling a suffix that has run out of characters must sort before any suffix that continues, so the missing rank has to be smaller than every real rank (use −1). Padding with a large value breaks ties the wrong way; with the pad set to 10⁹, banana comes out as [1,3,5,0,2,4] instead of [5,3,1,0,4,2].
Counting distinct substrings without subtracting the LCP
There are n(n+1)/2 = 21 prefixes of suffixes of banana, but only 15 distinct substrings, because the LCP column marks the prefixes that repeat the row above. Summing the LCP and subtracting gives the right count.
Where this shows up
Full-text search over a fixed corpus
When the text is indexed once and queried many times with different patterns, a suffix array turns each query into a binary search instead of a scan.
Longest repeated and common substrings
The largest LCP gives the longest repeat in one string. Joining two strings with a separator, then looking for the largest LCP between suffixes that come from different strings, gives their longest common substring.
Genomics and compression
DNA aligners and the Burrows-Wheeler transform both begin with the sorted order of suffixes or rotations of a long text, which is exactly the suffix array.
Contest and interview problems
Counting distinct substrings, the k-th smallest substring and “longest substring that appears at least twice” are all a few lines once SA and LCP exist.
SOLVE IT YOURSELF
Solve it: sort every suffix without comparing them
Sorting a string’s suffixes naively costs O(n² log n), because each comparison can scan the whole string. Sort by rank pairs and double the length each round, and it drops to O(n log² n). Python or TypeScript.
YOUR TASK
Implement suffix_array(s): return the starting indices of all suffixes of s in lexicographic order. "banana" gives [5, 3, 1, 0, 4, 2].
HINTS — 6 IDEAS
Round 0: rank each position by its own character. Now every suffix is sorted by its first 1 character.
Round k: sort by the pair(rank[i], rank[i+k]). Because both halves are already correctly ranked for length k, that pair sorts them for length 2k.
Use a sentinel like −1 when i + k runs off the end — a shorter suffix must sort before a longer one that shares its prefix.
Re-rank after each sort, giving equal pairs the same rank. That is what lets ties keep resolving in later rounds.
Stop when every rank is distinct — the order is final and further doubling changes nothing.
Lengths go 1, 2, 4, 8 …, so there are only log n rounds, each dominated by one sort.