Suffix Trees & Suffix Automata
Ukkonen’s algorithm, the suffix automaton, and what each one answers.
Knuth once conjectured that the longest common substring of two strings could not be found in linear time. Weiner refuted it in 1973 with a linear-size index of every suffix, the suffix tree. Its leaner cousin, the suffix automaton, is the smallest machine that recognizes every substring of a text, and for a text of length it never needs more than states.
What you’ll learn
- Define the suffix tree of , bound its size, and use it to answer substring, repeat and longest-common-substring questions in linear time.
- Explain Ukkonen's online construction (implicit trees, the three extension rules, suffix links, the active point) and why it takes time for a constant alphabet; place Weiner, McCreight and Farach.
- Define the suffix automaton through end-position classes, prove that it has at most states and transitions, and build it online.
- Count distinct substrings and occurrences and find longest common substrings with the automaton, and choose among suffix trees, automata and arrays.
Suffix trees: size and power
| Question | How | Time |
|---|---|---|
| Does occur? | walk down from the root | |
| How many times? | number of leaves below 's locus, precomputed | |
| Where? | list those leaves | |
| Longest repeated substring | an internal node of maximum string depth | |
| Longest common substring of and | in the tree of , the deepest internal node with leaves from both strings | |
| LCP of two suffixes | string depth of their leaves' lowest common ancestor | after preprocessing |
How many internal nodes, counting the root, does the suffix tree of banana$ have?
Show the answer
4
The root and the three right-branching repeats a (followed by $ or n), ana (followed by $ or n) and na (followed by $ or n). With the 7 leaves, the tree has 11 nodes, well within the bound of internal nodes.
Ukkonen's online construction
Ukkonen's algorithm reads left to right and keeps the implicit suffix tree of the prefix read so far: the radix tree of its suffixes, in which suffixes that are prefixes of other suffixes end inside the tree rather than at leaves. Phase reads and extends every suffix by , from the longest down, by one of three rules:
- The suffix ends at a leaf: extend the leaf edge.
- It ends at a locus with no continuation : add a leaf there (splitting the edge if the locus is inside one, which creates an internal node).
- The continuation already exists: do nothing.
Done naively that is extensions per phase, in all. Four observations make it linear.
| Trick | Why it works |
|---|---|
| Open-ended leaves: a leaf edge stores | once a leaf, always a leaf, so every rule-1 extension of a phase happens implicitly, at no cost |
| Rule 3 ends the phase | if already occurs, so does every shorter suffix followed by , as a suffix of that occurrence |
| Suffix links: internal node points to node | the next extension starts from the previous one's locus with one link jump instead of a walk from the root; is right-branching whenever is, so the target exists |
| Skip/count | walking down to a locus whose string is known to exist, compare only the first character of each edge and skip by edge lengths: one step per node, not per character |
Each explicit extension either creates a leaf (rule 2) or ends its phase (rule 3). There are leaves and phases:
Between consecutive extensions the algorithm moves up at most one edge, follows one suffix link, and walks down by skip/count. Measure the node depth of the current position (the number of nodes above it). Following a suffix link lowers it by at most 1, because distinct ancestors of map to distinct ancestors of ; so each move lowers it by at most 2, and it never exceeds :
With constant-time child lookups every step is . The bound is amortized: a single character can trigger extensions. Breslauer and Italiano (2013) bounded the worst case per character by a doubly logarithmic factor.
With characters that can only be compared, child lookups cost and the tree takes time. Farach (1997) showed that for integer alphabets the suffix tree can be built in time, so suffix trees can be built optimally for every alphabet; his algorithm builds the tree of the suffixes at odd positions recursively, derives the tree of the even ones from it, and merges the two, the same divide-and-conquer spirit that DC3 later brought to suffix arrays.
In phase , the extension of suffix finds that the next character already continues its path (rule 3). Why may Ukkonen's algorithm skip the extensions of all shorter suffixes in this phase?
- Because shorter suffixes always end at leaves
- Because the tree is implicit until the end, so missing extensions are fixed when the marker is added
- Because occurs earlier in the text, and every shorter suffix followed by is a suffix of that occurrence, so its path exists too
- Because the suffix link of the current node points to the root
Show the answer
C. Because occurs earlier in the text, and every shorter suffix followed by is a suffix of that occurrence, so its path exists too
Rule 3 means is already a path, that is, it occurs earlier in . For any , the string is a suffix of that occurrence, so it is a path as well: all remaining extensions of the phase are rule 3, and doing nothing is correct.
The suffix automaton
| End positions | Strings in the class | |
|---|---|---|
| (start state) | the empty string | 0 |
| a | 1 | |
| ab | 2 | |
| b | 1 | |
| abb | 3 | |
| bb | 2 | |
| bbb, abbb | 4 |
States. The online construction below adds, for each character, one new state and at most one clone (a split of an existing class). The first two characters never clone, because a clone needs a transition with , impossible while all lengths are at most 2. Counting the start state:
Transitions. Take a spanning tree of longest paths from the start state; it has edges. Map every other transition to the string (longest path to ) (longest path from to an accepting state): a suffix of , and different transitions give different suffixes. The whole string is never produced, since its path uses tree edges only, so there are at most non-tree transitions:
Reaching states forces the shape , which has fewer transitions, and this shaves the bound to for . Either way the automaton has size, against up to distinct substrings it recognizes.
def build_sam(s):
link, length, nxt = [-1], [0], [{}] # state 0: the empty string
last = 0
for ch in s:
cur = len(nxt)
nxt.append({}); length.append(length[last] + 1); link.append(0)
p = last
while p != -1 and ch not in nxt[p]: # new transitions into cur
nxt[p][ch] = cur
p = link[p]
if p != -1:
q = nxt[p][ch]
if length[p] + 1 == length[q]:
link[cur] = q
else: # split q's class: the clone keeps q's transitions
clone = len(nxt)
nxt.append(dict(nxt[q])); length.append(length[p] + 1); link.append(link[q])
while p != -1 and nxt[p].get(ch) == q:
nxt[p][ch] = clone
p = link[p]
link[q] = link[cur] = clone
last = cur
return link, length, nxtOnline: after each character the structure is the automaton of the prefix read so far. The work is amortized per character for a constant alphabet ( with ordered maps): the first loop adds transitions, of which there are in total, and the redirecting loop is paid for by a potential argument on the suffix-link path of last.
What the automaton answers, and which index to choose
- Distinct substrings. Classes partition the nonempty substrings, and class holds exactly of them, so the count is : 15 for banana. Added online, the new state of each character contributes the substrings that character creates.
- Occurrences. counts the occurrences of every string in class . Give each non-clone state a 1 (it is the class of a prefix of , ending where that prefix ends), then add every state's count to its suffix link, longest states first; to count , walk it from the start state.
- Longest common substring. Build the automaton of and read through it, keeping the current state and the length of the current match; on a missing transition, follow suffix links, which shorten the match as little as possible. Total .
def longest_common_substring(s, t):
link, length, nxt = build_sam(s)
v, l, best, end = 0, 0, 0, 0
for i, ch in enumerate(t):
while v and ch not in nxt[v]: # shorten the match along suffix links
v = link[v]
l = length[v]
if ch in nxt[v]:
v = nxt[v][ch]
l += 1
if l > best:
best, end = l, i
return t[end - best + 1:end + 1]longest_common_substring("xabcdey", "zbcdeabw") returns "bcde". The same walk gives the matching statistics of : for each position, the longest substring of that ends there.
| Need | Suffix array + LCP | Suffix tree | Suffix automaton |
|---|---|---|---|
| Memory | smallest: about integers | largest | at most states, transitions |
| Appending characters | rebuild | yes (Ukkonen) | yes, simplest code |
| Pattern search | |||
| Typical uses | sorting-based queries, -th substring, compressed indexes | repeats, tree traversals, LCA-based LCP queries | distinct substrings online, occurrence counts, matching statistics |
Key takeaways
- The suffix tree of is the radix tree of its suffixes: leaves, at most internal nodes, edge labels as index pairs, and pattern search for a constant alphabet.
- Ukkonen's algorithm builds it online in amortized : open-ended leaves make rule 1 free, rule 3 ends a phase, and suffix links with skip/count bound the walking by a depth potential. Farach made construction linear for integer alphabets.
- The suffix automaton's states are end-position classes: at most states and transitions, built online, with distinct substrings and occurrence counts summed up the link tree.
- The automaton's suffix-link tree is the suffix tree of the reversed string; choose the suffix array for memory, the automaton for online and counting tasks, the tree for traversal-heavy queries.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
About how many nodes can the suffix tree of a string of length (plus the end marker) have at most?
- About
- About
- About
- About
Show the answer
C. About
It has leaves and at most internal nodes, so at most nodes. The uncompressed suffix trie can have nodes, about here.
Why does Ukkonen's algorithm store every leaf edge as instead of ?
- To save memory on the end position
- Because leaves never acquire children, so every leaf grows by one character per phase, and an open end makes all those rule-1 extensions free
- Because the end of a leaf edge is unknown until the marker is added, and the algorithm cannot run without it
- To mark which leaves belong to repeated substrings
Show the answer
B. Because leaves never acquire children, so every leaf grows by one character per phase, and an open end makes all those rule-1 extensions free
"Once a leaf, always a leaf": a leaf's suffix is extended in every later phase, always by rule 1. With an open end pointing at the current phase, all of those extensions happen without touching the leaves, which is essential for the linear bound.
In the suffix automaton of abbb, which substring is in the same state as bbb?
- bb
- b
- None: every substring has its own state
- abbb
Show the answer
D. abbb
bbb and abbb both occur only ending at position 3, so they have the same end-position set and share a state. A class always consists of consecutive-length suffixes of its longest member, here abbb and bbb.
Why does count the distinct substrings of ?
- Because every state is reached by exactly one path from the start
- Because each class holds the suffixes of its longest string with lengths from to , and the classes partition the nonempty substrings
- Because is the number of occurrences of the strings in
- Because the suffix links form a path from every state to the start
Show the answer
B. Because each class holds the suffixes of its longest string with lengths from to , and the classes partition the nonempty substrings
Every nonempty substring belongs to exactly one end-position class, and a class with longest member of length contains exactly the suffixes of that member whose lengths exceed . Summing the sizes of the classes counts each substring once.
Further reading
- P. Weiner, "Linear pattern matching algorithms," Proceedings of the 14th IEEE Symposium on Switching and Automata Theory (1973), 1–11.
- E. Ukkonen, "On-line construction of suffix trees," Algorithmica 14(3) (1995), 249–260.
- M. Farach, "Optimal suffix tree construction with large alphabets," Proceedings of FOCS (1997), 137–143.
- A. Blumer, J. Blumer, D. Haussler, A. Ehrenfeucht, M. T. Chen & J. Seiferas, "The smallest automaton recognizing the subwords of a text," Theoretical Computer Science 40 (1985), 31–55.
- D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997), chapter 6.