Data Structures · Visualization
Suffix Array: Search
Suffix Array
Searching for a pattern in a suffix array uses binary search: since the suffixes are sorted alphabetically, a pattern that exists in the text must appear as the beginning of some contiguous block of suffixes in the array. Time: O(m log n), where m is the pattern length and n is the text length. Space: O(1) extra.
Big-O: Build O(n log n); pattern search O(m log n).
Suffix Array: Search
Suffix ArraySearching for a pattern in a suffix array uses binary search: since the suffixes are sorted alphabetically, a pattern that exists in the text must appear as the beginning of some contiguous block of suffixes in the array. Binary search quickly narrows down to that block by comparing the pattern against the beginning of suffixes at the midpoint.
How Search Works
- Set a search range covering the whole suffix array.
- Repeatedly check the suffix at the middle of the current range.
- Compare the pattern with the start of that suffix to decide whether to search the left or right half.
- Narrow the range until the pattern is found (as a prefix of some suffix) or the range is empty.
Search Worked Example
Input: Search for 'ana' in suffix array [5,3,1,0,4,2] over 'banana'
- Check the middle suffix, compare its start with 'ana'
- Narrow the search range based on alphabetical comparison
- Eventually land on suffix starting at index 3 ('ana...') and index 1 ('anana') — both start with 'ana'
Output: Pattern found at starting indices 3 and 1
Press ▶ Run to watch it step by step.
def search(sa, s, p):
# binary search over the sorted suffix array
lo, hi = 0, len(sa) - 1
while lo <= hi:
mid = (lo + hi) // 2
suffix = s[sa[mid]:]
if suffix.startswith(p): return True
if suffix < p: lo = mid + 1
else: hi = mid - 1
return False # O(m log n)
print(search(build_sa("banana"), "banana", "ana")) # True
# example: searchBehind 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.
Search Time & Space Complexity
When to Use Search
- Fast substring existence checks in large texts
- Finding every occurrence of a search term in a document instantly
- Search engines and text editors' 'find' functionality on large files
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.