Data Structures · Visualization
Suffix Array: Build
Suffix Array
Building a suffix array means generating every suffix of the string and sorting them alphabetically. Time: O(n log n) with an efficient (prefix-doubling) approach, O(n^2 log n) naive. Space: O(n).
Big-O: Build O(n log n); pattern search O(m log n).
Suffix Array: Build
Suffix ArrayBuilding a suffix array means generating every suffix of the string and sorting them alphabetically. A naive approach directly compares full suffixes (slow for long strings); faster approaches sort suffixes based on small prefixes first and progressively double the compared length each round, cutting the total work down significantly.
How Build Works
- Generate all n suffixes of the string, each paired with its starting index.
- Compare suffixes character by character to determine alphabetical order (or use a doubling technique for speed on large strings).
- Sort all suffixes using this comparison.
- Extract just the starting indices, in sorted order, as the final suffix array.
Build Worked Example
Input: String: 'abc'
- Suffixes: abc(0), bc(1), c(2)
- Sort alphabetically: abc(0), bc(1), c(2) — already in order
Output: [0, 1, 2]
Press ▶ Run to watch it step by step.
def build_sa(s):
n = len(s)
sa = list(range(n))
rank = list(map(ord, s)) # initial rank by char
k = 1
while k < n:
sa.sort(key=lambda i: (rank[i], rank[i + k] if i + k < n else -1))
tmp = [0] * n
for i in range(1, n): # assign new ranks
a, b = sa[i - 1], sa[i]
prev = (rank[a], rank[a + k] if a + k < n else -1)
cur = (rank[b], rank[b + k] if b + k < n else -1)
tmp[b] = tmp[a] + (prev != cur)
rank = tmp
k *= 2
return sa # O(n log n) prefix doubling
# example: buildBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Build Time & Space Complexity
When to Use Build
- The one-time preprocessing step enabling fast repeated text queries
- Preparing genome data for repeated pattern-matching queries
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.