Data Structures · Visualization
Suffix Array: Introduction
Suffix Array
A suffix array lists the starting positions of every suffix (the tail end of a string, from some position to the end) of a given string, sorted in alphabetical order. Time: O(n log n) to build with an efficient algorithm (naive sorting is O(n^2 log n)). Space: O(n).
Big-O: Build O(n log n); pattern search O(m log n).
Suffix Array: Introduction
Suffix ArrayA suffix array lists the starting positions of every suffix (the tail end of a string, from some position to the end) of a given string, sorted in alphabetical order. Once built, it makes tasks like searching for a substring, finding repeated patterns, or comparing text extremely fast, because all similar suffixes end up sitting next to each other in the sorted order.
How Suffix Array: Introduction Works
- List every suffix of the string, along with its starting index.
- Sort these suffixes alphabetically (lexicographically).
- Keep only the starting indices, in this sorted order — this is the suffix array.
Suffix Array: Introduction Worked Example
Input: String: 'banana'
- Suffixes: banana(0), anana(1), nana(2), ana(3), na(4), a(5)
- Sort alphabetically: a(5), ana(3), anana(1), banana(0), na(4), nana(2)
- Keep the starting indices in that order
Output: [5, 3, 1, 0, 4, 2]
Press ▶ Run to watch it step by step.
# Suffix array: sorted order of all suffixes
s = "banana"
suffixes = sorted((s[i:], i) for i in range(len(s)))
# [('a',5), ('ana',3), ('anana',1),
# ('banana',0), ('na',4), ('nana',2)]
print([idx for _, idx in suffixes]) # [5, 3, 1, 0, 4, 2]
# example: introSuffix Array: Introduction Time & Space Complexity
When to Use Suffix Array: Introduction
- Fast substring search in a large body of text (e.g. search engines, DNA analysis)
- Finding the longest repeated substring in a text
- Bioinformatics: analyzing DNA/protein sequences for patterns
- Data compression algorithms (e.g. Burrows-Wheeler transform)
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.