Data Structures · Visualization
Suffix Tree: Introduction
Suffix Tree
A suffix tree is a compressed trie containing every suffix of a string, letting substring, pattern, and repeat queries run in time proportional to the pattern length rather than the text length. Time: Build: O(n) with Ukkonen's algorithm; Search: O(m) for pattern length m. Space: O(n).
Big-O: Build O(n); substring search O(m) for pattern length m.
Suffix Tree: Introduction
Suffix TreeA suffix tree is a compressed trie containing every suffix of a string, letting substring, pattern, and repeat queries run in time proportional to the pattern length rather than the text length. It's built once (commonly via Ukkonen's linear-time algorithm) and reused for many queries — complementing the Suffix Array already on this site.
How Suffix Tree: Introduction Works
- Append a unique terminal symbol (e.g. '#x27;) to the string so no suffix is a prefix of another.
- Insert every suffix of the string into a shared trie.
- Compress non-branching chains of single-child nodes into single edges labeled with substrings (not single characters), which is what makes it a 'compressed' trie.
- Each leaf corresponds to exactly one suffix, and each root-to-leaf path spells that suffix.
Suffix Tree: Introduction Worked Example
Input: Build a suffix tree for "bananaquot;
- Suffixes: banana$, anana$, nana$, ana$, na$, a$, $
- Shared prefixes like 'ana' and 'na' merge into branching internal nodes
- The tree compresses 7 suffixes into a handful of branching edges
Output: A tree with O(n) nodes supporting substring search in O(m) for pattern length m
Press ▶ Run to watch it step by step.
def build_suffix_tree(s):
s += "quot; # terminal marker
suffixes = [s[i:] for i in range(len(s))]
root = {}
for i, suf in enumerate(suffixes):
cur = root
j = 0
while j < len(suf): # insert each suffix
ch = suf[j]
if ch not in cur:
cur[ch] = {"$end": i}
cur = cur[ch]
else:
cur = cur[ch]
if "$end" in cur:
del cur["$end"]
j += 1
return root # compressed trie of suffixes
# tree = build_suffix_tree("banana")
# pattern searches now only follow the pattern's chars
# example: build "bananaquot;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.
Suffix Tree: Introduction Time & Space Complexity
When to Use Suffix Tree: Introduction
- Genome sequence analysis (finding repeats, alignments)
- Plagiarism / longest common substring detection
- Full-text search engines
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.