Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 n≥2n \ge 2 it never needs more than 2n−12n - 1 states.

What you’ll learn

  • Define the suffix tree of s$s\$, 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 O(n)O(n) time for a constant alphabet; place Weiner, McCreight and Farach.
  • Define the suffix automaton through end-position classes, prove that it has at most 2n−12n - 1 states and 3n−43n - 4 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

QuestionHowTime
Does pp occur?walk pp down from the rootO(m)O(m)
How many times?number of leaves below pp's locus, precomputedO(m)O(m)
Where?list those leavesO(m+occ)O(m + \mathrm{occ})
Longest repeated substringan internal node of maximum string depthO(n)O(n)
Longest common substring of ss and ttin the tree of s#t$s\#t\$, the deepest internal node with leaves from both stringsO(∣s∣+∣t∣)O(\abs{s} + \abs{t})
LCP of two suffixesstring depth of their leaves' lowest common ancestorO(1)O(1) after O(n)O(n) preprocessing
Times assume a constant alphabet. Each internal node other than the root spells a right-branching repeat: a substring that occurs at least twice, followed by two different characters.
Predict before you look

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 n=6n = 6 internal nodes.

Ukkonen's online construction

Ukkonen's algorithm reads ss 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 ii reads c=s[i]c = s[i] and extends every suffix s[j..i−1]s[j..i-1] by cc, from the longest down, by one of three rules:

  1. The suffix ends at a leaf: extend the leaf edge.
  2. It ends at a locus with no continuation cc: add a leaf there (splitting the edge if the locus is inside one, which creates an internal node).
  3. The continuation cc already exists: do nothing.

Done naively that is Θ(n2)\Theta(n^2) extensions per phase, Θ(n3)\Theta(n^3) in all. Four observations make it linear.

TrickWhy it works
Open-ended leaves: a leaf edge stores (a,∞)(a, \infty)once a leaf, always a leaf, so every rule-1 extension of a phase happens implicitly, at no cost
Rule 3 ends the phaseif s[j..i−1] cs[j..i-1]\,c already occurs, so does every shorter suffix followed by cc, as a suffix of that occurrence
Suffix links: internal node cαc\alpha points to node α\alphathe next extension starts from the previous one's locus with one link jump instead of a walk from the root; α\alpha is right-branching whenever cαc\alpha is, so the target exists
Skip/countwalking 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
The active point (node, first character of the edge, length) records where the next phase starts its explicit extensions: the longest suffix of the current prefix that is not yet a leaf. At the end, adding $\$ turns the implicit tree into the true suffix tree.
DerivationWhy the total work is O(n) for a constant alphabet
  1. #explicit extensions  ≤  (n+1)+(n+1)=O(n)\#\text{explicit extensions} \;\le\; (n + 1) + (n + 1) = O(n)

    Each explicit extension either creates a leaf (rule 2) or ends its phase (rule 3). There are n+1n + 1 leaves and n+1n + 1 phases:

  2. #skip/count steps  ≤  n+2⋅#extensions=O(n)\#\text{skip/count steps} \;\le\; n + 2 \cdot \#\text{extensions} = O(n)

    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 cαc\alpha map to distinct ancestors of α\alpha; so each move lowers it by at most 2, and it never exceeds nn:

  3. T(n)=O(n) (amortized O(1) per character)T(n) = O(n) \ \text{(amortized } O(1) \text{ per character)}

    With constant-time child lookups every step is O(1)O(1). The bound is amortized: a single character can trigger Θ(n)\Theta(n) 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 O(log⁡∣Σ∣)O(\log \abs{\Sigma}) and the tree takes O(nlog⁡∣Σ∣)O(n \log \abs{\Sigma}) time. Farach (1997) showed that for integer alphabets {1,…,n}\{1, \dots, n\} the suffix tree can be built in O(n)O(n) 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.

Check your understanding

In phase ii, the extension of suffix s[j..i−1]s[j..i-1] finds that the next character cc already continues its path (rule 3). Why may Ukkonen's algorithm skip the extensions of all shorter suffixes in this phase?

  1. Because shorter suffixes always end at leaves
  2. Because the tree is implicit until the end, so missing extensions are fixed when the marker is added
  3. Because s[j..i−1] cs[j..i-1]\,c occurs earlier in the text, and every shorter suffix followed by cc is a suffix of that occurrence, so its path exists too
  4. Because the suffix link of the current node points to the root
Show the answer

C. Because s[j..i−1] cs[j..i-1]\,c occurs earlier in the text, and every shorter suffix followed by cc is a suffix of that occurrence, so its path exists too

Rule 3 means s[j..i−1] cs[j..i-1]\,c is already a path, that is, it occurs earlier in ss. For any j′>jj' > j, the string s[j′..i−1] cs[j'..i-1]\,c 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 positionsStrings in the classlen\mathrm{len}
(start state)the empty string0
{0}\{0\}a1
{1}\{1\}ab2
{1,2,3}\{1, 2, 3\}b1
{2}\{2\}abb3
{2,3}\{2, 3\}bb2
{3}\{3\}bbb, abbb4
The seven states of the suffix automaton of abbb: 2n−12n - 1 for n=4n = 4, the maximum. The last class holds two strings, abbb and its suffix bbb, which end at the same places; its suffix link goes to the class of bb.
DerivationProof sketches
  1. #states  ≤  1+2+2(n−2)=2n−1\#\text{states} \;\le\; 1 + 2 + 2(n - 2) = 2n - 1

    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 p→qp \to q with len(p)+1<len(q)\mathrm{len}(p) + 1 < \mathrm{len}(q), impossible while all lengths are at most 2. Counting the start state:

  2. #transitions  ≤  (2n−2)+(n−1)=3n−3\#\text{transitions} \;\le\; (2n - 2) + (n - 1) = 3n - 3

    Transitions. Take a spanning tree of longest paths from the start state; it has #states−1\#\text{states} - 1 edges. Map every other transition p→cqp \xrightarrow{c} q to the string (longest path to pp) cc (longest path from qq to an accepting state): a suffix of ss, and different transitions give different suffixes. The whole string ss is never produced, since its path uses tree edges only, so there are at most n−1n - 1 non-tree transitions:

  3. #states+#transitions=O(n)\#\text{states} + \#\text{transitions} = O(n)

    Reaching 2n−12n - 1 states forces the shape abn−1ab^{n-1}, which has fewer transitions, and this shaves the bound to 3n−43n - 4 for n≥3n \ge 3. Either way the automaton has O(n)O(n) size, against up to n(n+1)/2n(n+1)/2 distinct substrings it recognizes.

python
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, nxt

Online: after each character the structure is the automaton of the prefix read so far. The work is amortized O(1)O(1) per character for a constant alphabet (O(log⁡∣Σ∣)O(\log \abs{\Sigma}) with ordered maps): the first loop adds transitions, of which there are O(n)O(n) 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 vv holds exactly len(v)−len(link(v))\mathrm{len}(v) - \mathrm{len}(\mathrm{link}(v)) of them, so the count is ∑v≠start(len(v)−len(link(v)))\sum_{v \ne \text{start}} \big(\mathrm{len}(v) - \mathrm{len}(\mathrm{link}(v))\big): 15 for banana. Added online, the new state of each character contributes the substrings that character creates.
  • Occurrences. ∣endpos(v)∣\abs{\mathrm{endpos}(v)} counts the occurrences of every string in class vv. Give each non-clone state a 1 (it is the class of a prefix of ss, ending where that prefix ends), then add every state's count to its suffix link, longest states first; to count pp, walk it from the start state.
  • Longest common substring. Build the automaton of ss and read tt 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 O(∣s∣+∣t∣)O(\abs{s} + \abs{t}).
python
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 tt: for each position, the longest substring of ss that ends there.

NeedSuffix array + LCPSuffix treeSuffix automaton
Memorysmallest: about 2n2n integerslargestat most 2n−12n - 1 states, 3n−43n - 4 transitions
Appending charactersrebuildyes (Ukkonen)yes, simplest code
Pattern searchO(mlog⁡n)O(m \log n)O(m)O(m)O(m)O(m)
Typical usessorting-based queries, kk-th substring, compressed indexesrepeats, tree traversals, LCA-based LCP queriesdistinct substrings online, occurrence counts, matching statistics
In contests the suffix array and the automaton dominate: both fit in about 30 lines. In large-scale indexing, suffix arrays and their compressed descendants (next lesson) win on memory.

Key takeaways

  • The suffix tree of s$s\$ is the radix tree of its suffixes: n+1n + 1 leaves, at most nn internal nodes, edge labels as index pairs, and O(m)O(m) pattern search for a constant alphabet.
  • Ukkonen's algorithm builds it online in amortized O(n)O(n): 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 2n−12n - 1 states and 3n−43n - 4 transitions, built online, with distinct substrings ∑(len(v)−len(link(v)))\sum (\mathrm{len}(v) - \mathrm{len}(\mathrm{link}(v))) 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.

Question 1

About how many nodes can the suffix tree of a string of length 10610^6 (plus the end marker) have at most?

  1. About 5×10115 \times 10^{11}
  2. About 2×1072 \times 10^7
  3. About 2×1062 \times 10^6
  4. About 2.6×1072.6 \times 10^7
Show the answer

C. About 2×1062 \times 10^6

It has 106+110^6 + 1 leaves and at most 10610^6 internal nodes, so at most 2×106+12 \times 10^6 + 1 nodes. The uncompressed suffix trie can have Θ(n2)\Theta(n^2) nodes, about 5×10115 \times 10^{11} here.

Question 2

Why does Ukkonen's algorithm store every leaf edge as (a,∞)(a, \infty) instead of (a,b)(a, b)?

  1. To save memory on the end position
  2. 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
  3. Because the end of a leaf edge is unknown until the marker is added, and the algorithm cannot run without it
  4. 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.

Question 3

In the suffix automaton of abbb, which substring is in the same state as bbb?

  1. bb
  2. b
  3. None: every substring has its own state
  4. 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.

Question 4

Why does ∑v≠start(len(v)−len(link(v)))\sum_{v \ne \text{start}} \big(\mathrm{len}(v) - \mathrm{len}(\mathrm{link}(v))\big) count the distinct substrings of ss?

  1. Because every state is reached by exactly one path from the start
  2. Because each class holds the suffixes of its longest string with lengths from len(link(v))+1\mathrm{len}(\mathrm{link}(v)) + 1 to len(v)\mathrm{len}(v), and the classes partition the nonempty substrings
  3. Because len(v)−len(link(v))\mathrm{len}(v) - \mathrm{len}(\mathrm{link}(v)) is the number of occurrences of the strings in vv
  4. 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 len(link(v))+1\mathrm{len}(\mathrm{link}(v)) + 1 to len(v)\mathrm{len}(v), 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 len(v)\mathrm{len}(v) contains exactly the suffixes of that member whose lengths exceed len(link(v))\mathrm{len}(\mathrm{link}(v)). 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.