Data Structures · Visualization
Suffix Tree: Search
Suffix Tree
Searching a suffix tree for a pattern walks down from the root matching the pattern's characters against edge labels; if the walk completes without mismatch, the pattern occurs in the text, and the subtree below marks every occurrence. Time: O(m) for pattern length m, independent of text length n. Space: O(1) auxiliary beyond the tree.
Big-O: Build O(n); substring search O(m) for pattern length m.
Suffix Tree: Search
Suffix TreeSearching a suffix tree for a pattern walks down from the root matching the pattern's characters against edge labels; if the walk completes without mismatch, the pattern occurs in the text, and the subtree below marks every occurrence.
How Search Works
- Start at the root and the beginning of the pattern.
- At each step, find the child edge whose label starts with the next unmatched character.
- Match characters along that edge; if a mismatch occurs, the pattern is absent.
- If the whole pattern is consumed, the pattern exists — all leaves in the current subtree give its occurrence positions.
Search Worked Example
Input: Search for "ana" in the suffix tree of "bananaquot;
- From root, follow edge starting with 'a'
- Match 'a', then 'n', then 'a' along the compressed edges
- Pattern fully consumed at an internal node whose subtree has 2 leaves
Output: "ana" occurs at positions 1 and 3 in "banana"
Press ▶ Run to watch it step by step.
def search(tree, pattern):
cur = tree
for ch in pattern:
if ch not in cur:
return [] # mismatch — absent
cur = cur[ch]
leaves = []
def collect(node):
if "$end" in node:
leaves.append(node["$end"])
for k, v in node.items():
if k != "$end":
collect(v)
collect(cur) # subtree = occurrences
return sorted(leaves) # e.g. "ana" → [1, 3]
# search(tree, "ana") → [1, 3] in O(m)
# example: search "ana"Behind 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 repeated substring searches after one-time build cost
- Bioinformatics motif search
- Auto-suggest / longest repeated substring tools
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.