Suffix Trees
A suffix tree stores every suffix of a text in one compressed trie. Any pattern is found by walking down from the root in time proportional to the pattern alone, and repeats show up as internal nodes. The price is memory, which is why suffix arrays usually replace it in practice.
Every Suffix, Sharing Prefixes
A suffix tree is a trie containing every suffix of a string, compressed so that any path without a branch becomes a single edge. For a text of length n there are n suffixes, and indexing all of them at once is what makes the structure powerful: any substring of the text is a prefix of some suffix, so a query about substrings becomes a walk from the root.
The uncompressed version, a suffix trie, makes the idea clear but does not scale. It stores every suffix character by character, which takes O(n²) nodes: about n²/2, or half a trillion for a one-megabyte text. Compression is not an optimisation here; it is what makes the structure usable at all.
Path compression merges every chain of single-child nodes into one edge. That gives a hard bound: with a terminator there are exactly n leaves, one per suffix, and every internal node has at least two children, so there are fewer than n internal nodes and fewer than 2n nodes in total.
The second half of the trick is that edges do not store the substrings they represent. Storing them would reintroduce the O(n²) space. Instead each edge holds a pair of indices into the original text, a start and an end, so an edge of any length costs two integers. The text must be kept alongside the tree, and the structure is O(n) in space.
A terminal character — conventionally $, chosen to appear nowhere else — is appended to the text before construction. Without it a suffix that is a prefix of another suffix ends partway along an edge rather than at a leaf, and the one-leaf-per-suffix property fails. In banana, the suffix na is a prefix of nana; appending $ forces every suffix to end at its own leaf.
banana$has 7 leaves and 3 internal nodes (fora,naandana), 11 nodes with the root- A node never has two children whose edges start with the same character
- The suffix tree is the trie of all suffixes with its one-child chains merged; a trie of separate words is the same idea for a dictionary
Searching in Time Independent of the Text
To test whether a pattern of length m occurs in the text, walk down from the root matching the pattern's characters against the edge labels. If the walk consumes the whole pattern, the pattern occurs; if it hits a mismatch or runs out of edges, it does not.
The cost is O(m) for a fixed alphabet: proportional to the pattern, with no dependence on the length of the text. A 100-character pattern costs the same in a one-kilobyte text as in a one-gigabyte one. No scanning algorithm can offer that: KMP and Rabin–Karp are O(n + m) per search because they must read the text.
The distinction is about where the work is paid. A suffix tree spends O(n) once to build, then answers each query in O(m). KMP spends O(m) preprocessing per pattern and O(n) scanning per search. Search a text repeatedly and the tree wins decisively; search it once and building the tree is wasted effort.
Counting occurrences follows immediately. After the walk ends at some node, every leaf beneath it corresponds to one position where the pattern occurs, so the answer is the number of leaves in that subtree — precomputable in one pass so the count itself is O(1). The positions themselves are read from those leaves in O(k) for k occurrences.
The same structure answers questions that scanning handles badly. The longest repeated substring is the internal node with the longest path from the root, counted in characters, since an internal node means its path occurs in at least two places. A generalized suffix tree holds several texts at once, each ending in its own terminator ($, #); the longest common substring of two texts is the deepest node with leaves from both. Both answers are one traversal of a tree already built.
| Preprocess | Per search | Best for | |
|---|---|---|---|
| Suffix tree | O(n) on the text | O(m) | Many patterns, one fixed text |
| KMP | O(m) on the pattern | O(n) | One pattern, streaming text |
| Rabin–Karp | O(m) | O(n) expected | Many patterns at once |
| Naive scan | None | O(n·m) | Tiny inputs only |
- A search can end inside an edge; the leaves below that edge are still the occurrences
- With alphabet size σ stored as sorted lists, each step picks a child in O(log σ), so the bound is O(m log σ)
- Practice: number of distinct substrings, repeated DNA sequences
Ukkonen's Linear-Time Construction
Building the tree naively — inserting each of the n suffixes one at a time — costs O(n²). Ukkonen's algorithm achieves O(n) and is widely considered one of the harder standard algorithms to implement correctly, so understanding what it does matters more than reproducing it.
It is online: it reads the text one character at a time, and after each character it holds an implicit suffix tree of the prefix read so far, one where some suffixes still end inside edges because the terminator has not arrived. Three ideas give the linear bound.
Implicit extension via a global end. When a new character arrives, every existing leaf edge must be extended by it. Rather than touching each leaf — which alone would be O(n) per character — leaf edges store their end as a shared pointer to a global variable. Incrementing that one variable extends every leaf simultaneously in O(1).
Suffix links. After splitting an edge to insert the suffix starting at position i, the algorithm must next work on the suffix starting at i+1. A suffix link from a node representing xα to the node representing α lets it jump there directly instead of descending from the root, which is what removes the repeated root-to-node walks.
Skipping resolved work. Once a suffix has been explicitly inserted, later phases need not revisit it; the algorithm tracks how far it has progressed and resumes rather than restarting. The total work across all phases telescopes to O(n) even though individual phases vary.
Two other linear-time builds are worth naming. Weiner's algorithm (1973) was the first, working right to left. McCreight's algorithm (1976) also runs in O(n) but needs the whole text up front, and is often called easier to follow; Ukkonen's online property is what suits streaming input.
- The naive build in the code inserts one suffix at a time: O(n²), fine for short texts
- The active point (node, edge, length) records where the next extension happens
- Suffix links point from the node for
xαto the node forα, for example fromanatonainbanana$
Terms, operations, and practical uses
Structure
- Suffix TrieA standard Trie containing all suffixes of a text. Has O(N²) nodes, making it unusable for large documents.
- Path CompressionMerging all nodes that have only one child into a single edge that represents a substring instead of a character.
- Implicit NodesA location along a compressed edge. Search algorithms can stop 'inside' an edge without a physical node existing there.
Capabilities
- O(M) SearchSearching for a pattern of length M takes O(M) time for a fixed alphabet, independent of the text length N.
- Suffix LinksPointers from an internal node representing string
awto the internal node representingw. Crucial for linear construction. - Generalized TreeA single Suffix Tree can index multiple documents by appending unique terminal characters (like
$and#) to each text.
Ukkonen's Algorithm
- Online ConstructionBuilds the tree character by character from left to right, allowing processing of streaming text.
- Active PointA triplet
(active_node, active_edge, active_length)that tracks exactly where the next character insertion should occur. - Linear TimeDespite complex internal rules (extension rules, active point updates), amortized analysis proves it builds the tree in O(N) time.
Code in Python, C++ and Java
class Node:
def __init__(self, start, end, suffix=-1):
self.start, self.end = start, end # edge label is text[start:end]
self.suffix = suffix # leaf: where its suffix starts
self.children = {}
def build(text):
root = Node(0, 0)
for i in range(len(text)): # insert suffix i, O(n) each
node, j = root, i
while True:
child = node.children.get(text[j])
if child is None:
node.children[text[j]] = Node(j, len(text), i)
break
k = child.start
while k < child.end and text[k] == text[j]:
k += 1
j += 1
if k == child.end:
node = child
continue
mid = Node(child.start, k) # split the edge where they differ
node.children[text[child.start]] = mid
child.start = k
mid.children[text[k]] = child
mid.children[text[j]] = Node(j, len(text), i)
break
return root
def leaves(node):
if not node.children:
return [node.suffix]
return [s for c in sorted(node.children) for s in leaves(node.children[c])]
def search(root, text, p):
node, j = root, 0
while j < len(p):
child = node.children.get(p[j])
if child is None:
return []
for k in range(child.start, child.end):
if j == len(p):
break
if text[k] != p[j]:
return []
j += 1
node = child
return sorted(leaves(node))
def longest_repeat(node, text, path=''):
best = path
for c in node.children.values():
if c.children: # internal: its path occurs twice or more
label = path + text[c.start:c.end]
cand = longest_repeat(c, text, label)
if len(cand) > len(best):
best = cand
return best
def count_internal(node):
return sum(1 + count_internal(c) for c in node.children.values() if c.children)
text = 'banana$'
root = build(text)
print('leaves', len(leaves(root)), 'internal nodes', count_internal(root))
for p in ['ana', 'nan', 'nab']:
print('search', p, search(root, text, p))
print('longest repeated substring', longest_repeat(root, text))
print('leaves left to right', leaves(root))#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
int start, end, suffix; // edge label is text[start, end)
map<char, Node*> children;
Node(int s, int e, int suf = -1) : start(s), end(e), suffix(suf) {}
};
Node* build(const string& text) {
int n = text.size();
Node* root = new Node(0, 0);
for (int i = 0; i < n; i++) { // insert suffix i, O(n) each
Node* node = root;
int j = i;
while (true) {
auto it = node->children.find(text[j]);
if (it == node->children.end()) {
node->children[text[j]] = new Node(j, n, i);
break;
}
Node* child = it->second;
int k = child->start;
while (k < child->end && text[k] == text[j]) { k++; j++; }
if (k == child->end) { node = child; continue; }
Node* mid = new Node(child->start, k); // split the edge where they differ
node->children[text[child->start]] = mid;
child->start = k;
mid->children[text[k]] = child;
mid->children[text[j]] = new Node(j, n, i);
break;
}
}
return root;
}
void leaves(Node* node, vector<int>& out) {
if (node->children.empty()) { out.push_back(node->suffix); return; }
for (auto& [c, child] : node->children) leaves(child, out);
}
vector<int> search(Node* root, const string& text, const string& p) {
Node* node = root;
size_t j = 0;
while (j < p.size()) {
auto it = node->children.find(p[j]);
if (it == node->children.end()) return {};
Node* child = it->second;
for (int k = child->start; k < child->end && j < p.size(); k++, j++)
if (text[k] != p[j]) return {};
node = child;
}
vector<int> out;
leaves(node, out);
sort(out.begin(), out.end());
return out;
}
string longestRepeat(Node* node, const string& text, const string& path) {
string best = path;
for (auto& [c, child] : node->children) {
if (child->children.empty()) continue; // internal: its path occurs twice or more
string cand = longestRepeat(child, text, path + text.substr(child->start, child->end - child->start));
if (cand.size() > best.size()) best = cand;
}
return best;
}
int countInternal(Node* node) {
int c = 0;
for (auto& [ch, child] : node->children)
if (!child->children.empty()) c += 1 + countInternal(child);
return c;
}
string list(const vector<int>& v) {
string s = "[";
for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
return s + "]";
}
int main() {
string text = "banana$";
Node* root = build(text);
vector<int> all;
leaves(root, all);
cout << "leaves " << all.size() << " internal nodes " << countInternal(root) << '\n';
for (string p : {"ana", "nan", "nab"})
cout << "search " << p << " " << list(search(root, text, p)) << '\n';
cout << "longest repeated substring " << longestRepeat(root, text, "") << '\n';
cout << "leaves left to right " << list(all) << '\n';
}import java.util.*;
public class Main {
static class Node {
int start, end, suffix; // edge label is text[start, end)
TreeMap<Character, Node> children = new TreeMap<>();
Node(int s, int e, int suf) { start = s; end = e; suffix = suf; }
}
static Node build(String text) {
int n = text.length();
Node root = new Node(0, 0, -1);
for (int i = 0; i < n; i++) { // insert suffix i, O(n) each
Node node = root;
int j = i;
while (true) {
Node child = node.children.get(text.charAt(j));
if (child == null) {
node.children.put(text.charAt(j), new Node(j, n, i));
break;
}
int k = child.start;
while (k < child.end && text.charAt(k) == text.charAt(j)) { k++; j++; }
if (k == child.end) { node = child; continue; }
Node mid = new Node(child.start, k, -1); // split the edge where they differ
node.children.put(text.charAt(child.start), mid);
child.start = k;
mid.children.put(text.charAt(k), child);
mid.children.put(text.charAt(j), new Node(j, n, i));
break;
}
}
return root;
}
static void leaves(Node node, List<Integer> out) {
if (node.children.isEmpty()) { out.add(node.suffix); return; }
for (Node child : node.children.values()) leaves(child, out);
}
static List<Integer> search(Node root, String text, String p) {
Node node = root;
int j = 0;
while (j < p.length()) {
Node child = node.children.get(p.charAt(j));
if (child == null) return new ArrayList<>();
for (int k = child.start; k < child.end && j < p.length(); k++, j++)
if (text.charAt(k) != p.charAt(j)) return new ArrayList<>();
node = child;
}
List<Integer> out = new ArrayList<>();
leaves(node, out);
Collections.sort(out);
return out;
}
static String longestRepeat(Node node, String text, String path) {
String best = path;
for (Node child : node.children.values()) {
if (child.children.isEmpty()) continue; // internal: its path occurs twice or more
String cand = longestRepeat(child, text, path + text.substring(child.start, child.end));
if (cand.length() > best.length()) best = cand;
}
return best;
}
static int countInternal(Node node) {
int c = 0;
for (Node child : node.children.values())
if (!child.children.isEmpty()) c += 1 + countInternal(child);
return c;
}
public static void main(String[] args) {
String text = "banana$";
Node root = build(text);
List<Integer> all = new ArrayList<>();
leaves(root, all);
System.out.println("leaves " + all.size() + " internal nodes " + countInternal(root));
for (String p : new String[] {"ana", "nan", "nab"})
System.out.println("search " + p + " " + search(root, text, p));
System.out.println("longest repeated substring " + longestRepeat(root, text, ""));
System.out.println("leaves left to right " + all);
}
}Step through it
Running on text "banana$", search "ana", "nan" and "nab"
Why Suffix Arrays Usually Win
On paper the tree wins: O(m) search and O(n) construction. In practice the suffix tree vs suffix array choice usually goes the other way, and the reason is how much memory 'O(n)' really is.
A suffix tree node carries child pointers, a suffix link, and edge indices. With an alphabet of size σ, child storage is either an array of σ pointers per node — fast but enormous — or a hash map, which is smaller but slower and less cache-friendly. Realistic implementations consume 10 to 20 bytes per input character, so a one-gigabyte text needs 10 to 20 gigabytes of structure.
A suffix array keeps only the sorted start positions: 4 or 8 bytes per character, about three to five times smaller, and in one contiguous block that the cache handles well.
The cost is query time. Binary search over the sorted suffixes is O(m log n) rather than O(m), and an LCP array beside it brings that to O(m + log n), which recovers most of what the tree offered.
So the practical rule: suffix arrays are the default, and suffix trees are chosen when the work genuinely needs tree structure, such as repeats, matching across several texts, or algorithms that walk internal nodes. Genome comparison tools such as MUMmer used suffix trees for exactly this. Modern read aligners such as BWA and Bowtie use the compressed FM-index instead, which is smaller than either.
| Suffix tree | Suffix array | |
|---|---|---|
| Space | 10–20 bytes per character | 4–8 bytes per character |
| Search | O(m) | O(m log n), or O(m + log n) with LCP |
| Construction | O(n), hard to implement | O(n log n) simply, O(n) with effort |
| Locality | Pointer chasing | Contiguous, cache-friendly |
| Choose when | Structural queries on internal nodes | Almost everything else |
- Space: 10–20 bytes per character for the tree, 4–8 for the array
- The array is the tree's leaves read left to right (see the last tracer step)
- Choose the tree for structural queries; the array for plain search over large texts