Hey guys,
If you've ever tried learning Suffix Automaton (SAM), you probably know how painful it is to wrap your head around. I want to try explaining it from a different angle here.
Note: Some math terms and symbols in this post may be used loosely to keep things simple.
1. Basic definitions
Take two different strings $$$A$$$ and $$$B$$$ in $$$\Sigma^*$$$. We write $$$A \lt B$$$ (or $$$B \gt A$$$) if $$$A$$$ is a proper suffix of $$$B$$$. That means $$$A$$$ is a suffix of $$$B$$$ and $$$|A| \lt |B|$$$.
Examples: "bc" < "abc"; "a" < "aaa".
Now let $$$F$$$ be a non-empty set of distinct strings that includes the empty string $$$\varepsilon$$$. Every non-empty string $$$A \in F$$$ has at least one "smaller" string in $$$F$$$ (since $$$\varepsilon \in F$$$). Call $$$\text{Par}(A)$$$ the parent (immediate predecessor) of $$$A$$$. It is the longest string in $$$F$$$ that is smaller than $$$A$$$. In other words, $$$A \gt \text{Par}(A)$$$, and no $$$A' \in F$$$ satisfies $$$A \gt A' \gt \text{Par}(A)$$$.
Example: Let $$$F_1 = \lbrace\varepsilon, \text{"a"}, \text{"b"}, \text{"ab"}, \text{"ba"}, \text{"cab"}, \text{"cba"}, \text{"caba"}\rbrace$$$.
The strings smaller than "caba" in $$$F_1$$$ are $$$\lbrace\varepsilon, \text{"a"}, \text{"ba"}\rbrace$$$. The longest one is "ba", so $$$\text{Par}(\text{"caba"}) = \text{"ba"}$$$. In the same way: $$$\text{Par}(\text{"cab"}) = \text{"ab"}$$$, $$$\text{Par}(\text{"cba"}) = \text{"ba"}$$$, $$$\text{Par}(\text{"ba"}) = \text{"a"}$$$, and $$$\text{Par}(\text{"a"}) = \varepsilon$$$.
Next, let's build a graph called a Hasse diagram. Each string $$$A \in F$$$ becomes a node. For every $$$A \ne \varepsilon$$$, we connect $$$A$$$ to $$$\text{Par}(A)$$$. This always gives us a tree with root $$$\varepsilon$$$. Why? Each non-empty node connects to exactly one strictly shorter parent, so there are no cycles. Follow parent links up from any node, and you always reach $$$\varepsilon$$$.

Figure 1: Hasse diagram of F₁.
2. Building the Hasse diagram for all substrings of a string
Let $$$F$$$ be the set of all distinct substrings of a string $$$S$$$ (including $$$\varepsilon$$$). Our goal is to build the Hasse diagram of $$$F$$$. Two questions come up right away:
- Why do we want this Hasse diagram? What can it solve?
- How do we build it with optimal time and memory?
Before answering both questions, let's look at a simple (unoptimized) way to build it. We go left to right: build the tree for $$$S[1 \dots 1]$$$, then expand it to $$$S[1 \dots 2]$$$, and keep going until $$$S[1 \dots n]$$$.
Suppose we are at step $$$i$$$. We already have the Hasse diagram for $$$S[1 \dots i]$$$, and we want to update it for $$$S[1 \dots i+1]$$$. Every new substring ends at index $$$i+1$$$. So we insert the suffixes $$$S[1 \dots i+1], S[2 \dots i+1], \dots, S[i+1 \dots i+1]$$$ one by one:
- First, check $$$S[1 \dots i+1]$$$: Its length is $$$i + 1$$$, which is longer than every string in the old tree (max length $$$i$$$). So it is brand new and must be a leaf. We create a new node for it.
- Next, check $$$S[2 \dots i+1]$$$: There are two cases:
- Case 1: $$$S[2 \dots i+1]$$$ is not in the old tree yet. We create a new node for it and attach it as the parent of $$$S[1 \dots i+1]$$$. It cannot become the parent of any old node, because its length is $$$i$$$ and no old string is longer than $$$i$$$.
- Case 2: $$$S[2 \dots i+1]$$$ is already in the old tree. We keep strings distinct, so we do not create a new node. Instead, we attach $$$S[1 \dots i+1]$$$ directly to the existing node $$$S[2 \dots i+1]$$$ and stop. All shorter suffixes ($$$S[3 \dots i+1], \dots, S[i+1 \dots i+1]$$$) are suffixes of $$$S[2 \dots i+1]$$$, so they are already in the tree too.
- In general, for $$$S[k \dots i+1]$$$ ($$$k = 3, \dots, i+1$$$): The same logic applies. If $$$S[k \dots i+1]$$$ is not in the old tree, we create a new node and make it the parent of $$$S[k-1 \dots i+1]$$$. It can never become the parent of an old node $$$X$$$ either. If $$$S[k \dots i+1]$$$ were a suffix of a substring $$$X$$$ of $$$S[1 \dots i]$$$, then $$$S[k \dots i+1]$$$ would already be in $$$S[1 \dots i]$$$ (contradiction). As soon as we hit the first index $$$k^*$$$ where $$$S[k^* \dots i+1]$$$ already exists in the old tree (or we reach the root $$$\varepsilon$$$), we attach our last new node $$$S[k^* - 1 \dots i+1]$$$ to $$$S[k^* \dots i+1]$$$ and stop.
So every step looks the same. Adding $$$S[i+1]$$$ creates a vertical chain of new nodes $$$S[1 \dots i+1], S[2 \dots i+1], \dots$$$ until we hit the first index $$$k^*$$$ where $$$S[k^* \dots i+1] = S[l \dots r]$$$ already exists as some node $$$v$$$. Then we connect $$$u = S[k^* - 1 \dots i+1]$$$ to $$$v$$$ and stop.

Figure 2: Expanding the Hasse diagram from "ab" to "aba".
2.1. Generators of the Hasse tree and answer to question 1
Look at how we built the tree above. Every node comes from a prefix of $$$S$$$ or one of its suffixes. So we can call the prefixes $$$P_1 = S[1 \dots 1], P_2 = S[1 \dots 2], \dots, P_n = S[1 \dots n]$$$ the generators of the Hasse diagram.
This directly answers our first question: why is this tree useful?
Let's color the prefix nodes $$$P_1, P_2, \dots, P_n$$$ blue in the Hasse diagram of "abba" ($$$P_1 = \text{"a"}$$$, $$$P_2 = \text{"ab"}$$$, $$$P_3 = \text{"abb"}$$$, $$$P_4 = \text{"abba"}$$$):

Figure 3: Hasse diagram of "abba" (prefix nodes in blue).
Pick any node $$$u$$$ in this tree. Suppose the subtree of $$$u$$$ (including $$$u$$$ itself) contains a blue prefix node $$$P_k = S[1 \dots k]$$$. That means $$$u$$$ is a suffix of $$$S[1 \dots k]$$$. In other words, $$$u$$$ appears in $$$S$$$ ending at index $$$k$$$. The reverse is also true: every occurrence of $$$u$$$ ending at $$$k$$$ matches a unique blue node $$$P_k$$$ inside the subtree of $$$u$$$.
Thanks to this 1-to-1 match, we can read off many classic string queries right from the tree:
- Number of occurrences of $$$u$$$ in $$$S$$$: Count the blue nodes in the subtree of $$$u$$$ (including $$$u$$$). For
"abba", the subtree of"a"has 2 blue nodes ($$$P_1$$$ and $$$P_4$$$), and the subtree of"b"has 2 blue nodes ($$$P_2$$$ and $$$P_3$$$). So both"a"and"b"appear twice. - First and last end positions of $$$u$$$: Take the $$$\min$$$ and $$$\max$$$ index $$$k$$$ among the blue nodes $$$P_k$$$ in the subtree of $$$u$$$. (Subtract $$$|u| - 1$$$ to get the start position.)
- Total distinct non-empty substrings of $$$S$$$: Count all nodes in the tree except the root $$$\varepsilon$$$. Every other node is one distinct substring.
- Longest common suffix of two prefixes $$$P_i$$$ and $$$P_j$$$: Just find their lowest common ancestor $$$\text{LCA}(P_i, P_j)$$$ in the tree.
- Many other applications: Plenty of other substring problems can be solved on this tree as well.
This Hasse tree solves almost every substring problem cleanly. There is just one big catch: it can have up to $$$O(n^2)$$$ nodes. So how do we compress it (without losing these queries) and speed up its construction?
3. From Hasse tree to Suffix Automaton
Let $$$T_i$$$ be the Hasse tree for the prefix $$$P_i = S[1 \dots i]$$$. Each time we append $$$c = S[i+1]$$$ to $$$T_i$$$, we grow a vertical chain of new suffixes $$$S[1 \dots i+1], S[2 \dots i+1], \dots$$$ and attach it to an existing suffix in $$$T_i$$$.
Let's name that attachment point. Call $$$w_i$$$ the smallest index $$$k$$$ such that the suffix $$$S[k \dots i]$$$ already appeared earlier in $$$S[1 \dots i-1]$$$, meaning $$$S[l \dots r] = S[k \dots i]$$$ for some $$$r \lt i$$$. (If $$$S[i]$$$ is brand new, we set $$$w_i = i + 1$$$, which stands for $$$\varepsilon$$$.) Then the node $$$W_i = S[w_i \dots i]$$$ is the cut point at step $$$i$$$.
3.1. Climbing the tree
First, let's look at finding the cut point $$$w_{i+1}$$$ (we call this "climbing the tree") when adding $$$c = S[i+1]$$$ to $$$T_i$$$. Instead of starting from $$$k = 1$$$ (the bottom $$$P_i$$$) every time, let's compare $$$w_{i+1}$$$ and $$$w_i$$$ directly on the string $$$S[1 \dots i+1]$$$:

Figure 4: Chopping the last cell shows wᵢ ≤ wᵢ₊₁.
- Look at Figure 4: when $$$W_{i+1} = S[w_{i+1} \dots i+1]$$$ has length at least $$$2$$$, it matches an earlier block $$$S[l \dots r] = S[w_{i+1} \dots i+1]$$$ with $$$r \le i$$$ (top bar). Chop off the last cell $$$S[i+1]$$$ from both red blocks (middle bar). The two remaining blocks $$$S[l \dots r-1] = S[w_{i+1} \dots i]$$$ are still equal, and both sit inside $$$S[1 \dots i]$$$ with $$$r - 1 \lt i$$$ (bottom bar). So $$$S[w_{i+1} \dots i]$$$ already appeared earlier in $$$S[1 \dots i-1]$$$. (And if $$$|W_{i+1}| \le 1$$$, then $$$w_{i+1} \ge i + 1 \ge w_i$$$ already holds.) Since $$$w_i$$$ is the smallest index with that property at step $$$i$$$, we always get:
This gives us two quick wins:
- No need to start from the bottom $$$P_i$$$: No index $$$k \lt w_i$$$ can be the cut point at step $$$i+1$$$. Also, $$$S[k \dots i+1] = S[k \dots i] \cdot c$$$. So on $$$T_i$$$, we start right at $$$W_i = S[w_i \dots i]$$$ and climb up parent links ($$$k = w_i, w_i + 1, \dots$$$) until we hit the first $$$k^* = w_{i+1}$$$ with $$$S[k^* \dots i] \cdot c \in T_i$$$.
- Total climb steps are $$$O(n)$$$: Each climb step increases $$$k$$$ by $$$1$$$. (If $$$c$$$ is new, we climb past $$$\varepsilon$$$ and stop at $$$w_{i+1} = i + 2$$$.) Since $$$2 = w_1 \le w_2 \le \dots \le w_n \le n + 1$$$, the total climb steps over all $$$n$$$ characters are at most $$$n = O(n)$$$. Counting the stopping check at each step, we check at most $$$2n = O(n)$$$ candidates in total.
3.2. The last two bottlenecks
Climbing now takes $$$O(n)$$$ steps in total. Only two bottlenecks are left:
Right-append queries: At each candidate $$$v$$$ (at most $$$2n$$$ times), how do we answer this in $$$O(1)$$$?
"Is $$$v \cdot c$$$ in $$$T_i$$$, and if so, which node is it?"
The Hasse tree only stores left-append links ($$$x \mapsto a \cdot x$$$). It does not know right-append links ($$$v \mapsto v \cdot c$$$). If we walk down from the root every time to search for $$$v \cdot c$$$, each check takes $$$O(|v|)$$$, pushing us back to $$$O(n^2)$$$.
Attaching the new chain: Even after we find $$$W_{i+1}$$$ in amortized $$$O(1)$$$, the uncompressed tree $$$T_i$$$ still forces us to create the new chain $$$u_{k^{\ast}-1} \to \dots \to u_1$$$ one node at a time ($$$k^{\ast} = w_{i+1}$$$). That takes $$$w_{i+1} - 1$$$ steps each round, keeping both time and memory at $$$O(n^2)$$$.
3.3. Caching right-appends at each node (next[v][c])
Instead of searching for $$$v \cdot c$$$ again and again, let's cache the answer right at each node $$$v$$$ (just like dynamic programming).
At each node $$$v \in T_i$$$, we store a pointer table $$$\text{next}(v, c)$$$. It points directly to the node for $$$v \cdot c$$$ if $$$v \cdot c \in T_i$$$, or NULL otherwise. On the Hasse diagram, think of $$$\text{next}(v, c)$$$ as a one-way "fake" edge from $$$v$$$ to $$$v \cdot c$$$. It is not a real tree edge. We only add it to speed up the algorithm.
- Query cost: Now $$$O(1)$$$, since we just read $$$\text{next}(v, c)$$$.
- New question: When $$$T_i$$$ grows into $$$T_{i+1}$$$ after adding $$$c = S[i+1]$$$, which $$$\text{next}(x, a)$$$ entries change, and how do we update them?
Counting the next changes at step $$$i+1$$$
At step $$$i+1$$$ (let $$$k^* = w_{i+1}$$$), the new nodes form one vertical chain:
(if $$$c$$$ never appeared in $$$S[1 \dots i]$$$, then $$$k^{\ast} = w_{i+1} = i + 2$$$, so $$$u_{i+1} = c$$$ and $$$v_{i+1} = \varepsilon$$$).
Let's check every possible change to next across the whole tree:
- Every new node $$$u_k$$$ has $$$\text{next}(u_k, a) = \text{NULL}$$$ for all $$$a$$$: If $$$u_k \cdot a = S[l \dots r] \in T_{i+1}$$$ ($$$r \le i + 1$$$), then $$$u_k = S[l \dots r - 1]$$$ with $$$r - 1 \le i$$$. That puts $$$u_k \in T_i$$$, which is impossible since $$$u_k$$$ is new.
- No $$$\text{next}(x, a)$$$ with $$$a \ne c$$$ changes: Existing strings in $$$T_i$$$ keep their nodes, so $$$\text{next}(x, a)$$$ only changes when $$$x \cdot a$$$ is a new string at step $$$i+1$$$, and every new string ends with $$$c$$$.
- For character $$$c$$$, the nodes to update form one unbroken vertical chain: Each new string $$$u_k$$$ splits uniquely as $$$v_k \cdot c$$$. So the nodes in $$$T_i$$$ that need an update are $$$v_1, v_2, \dots, v_{k^*-1}$$$, with the assignment $$$\text{next}(v_k, c) \leftarrow u_k$$$.
3.4. Time and memory share the same root cause
Look at what we just counted. At step $$$i+1$$$, we create $$$k^* - 1$$$ new nodes ($$$u_1 \dots u_{k^*-1}$$$) and update $$$k^* - 1$$$ fake edges ($$$v_1 \dots v_{k^*-1}$$$). Both can be $$$O(n)$$$ per step, so over $$$n$$$ steps we are still stuck at $$$O(n^2)$$$.
Now both original problems point to the exact same culprit:
- Problem 1 ($$$O(n^2)$$$ memory): We store every substring in its own node, and a string of length $$$n$$$ can have $$$O(n^2)$$$ distinct substrings.
- Problem 2 ($$$O(n^2)$$$
nextupdates): We assignnextone node at a time along the chain $$$v_1 \dots v_{k^*-1}$$$.
This leads to a very natural idea: compress each chain of consecutive nodes into a single node. Then the new chain $$$u_1 \dots u_{k^*-1}$$$ shrinks into $$$1$$$ node (call it cur). The chain created in the previous step also shrinks into $$$1$$$ node (call it last). We no longer need to create or update nodes one by one along those chains.
3.5. Compressing the Hasse tree
Following that idea, let's compress chains of consecutive nodes into single nodes. Still, we need to check if this compression really works. Does it shrink memory enough, and does it keep our next optimization and substring queries intact? Let's check step by step.
First, why can we compress the Hasse tree? Nodes in the uncompressed tree do not appear at random: each time we add a prefix $$$P_j$$$, it grows a whole vertical chain of consecutive nodes at once. Because of that, consecutive nodes are often generated together by the exact same prefixes among $$$P_1, P_2, \dots, P_n$$$.
For each node $$$v$$$ in the uncompressed tree $$$T_i$$$, let $$$G(v)$$$ be its generator set, meaning the set of all prefix nodes $$$P_j$$$ inside the subtree of $$$v$$$ (including $$$v$$$ itself). Figure 5 shows $$$G(v)$$$ for several nodes in the Hasse tree of "abacab":

Figure 5: Generator sets G(v) on the Hasse tree of "abacab" (prefix nodes P₁…P₆ are colored blue).
Looking at Figure 5, a natural guess jumps out: keeping the root $$$\varepsilon$$$ at the top, non-empty substrings with the same generator set $$$G(v)$$$ behave alike, so we can merge all of them into one compressed node.
On any uncompressed Hasse tree, what does a group of non-empty nodes with the same $$$G(v)$$$ look like?
- If $$$x$$$ is an ancestor of $$$y$$$, then the subtree of $$$y$$$ sits inside the subtree of $$$x$$$, so $$$G(y) \subseteq G(x)$$$.
- For $$$G(x) = G(y)$$$, the path from $$$x$$$ down to $$$y$$$ cannot branch (every substring is a suffix of some $$$P_k$$$, so any side branch ends at a leaf $$$P_k$$$ outside $$$G(y)$$$, making $$$G(x)$$$ bigger than $$$G(y)$$$) and cannot contain a generator in the middle (if a node above $$$y$$$ is a prefix $$$P_k$$$, then $$$P_k \in G(x)$$$ but $$$P_k \notin G(y)$$$).
- Conversely, all non-empty nodes along a vertical path with no branching and no generator in the middle share the same generator set (a generator, if present, only sits at the bottom of the path).
So grouping non-empty nodes with the same $$$G(v)$$$ (while keeping the root $$$\lbrace\varepsilon\rbrace$$$ as the root) is the exact same rule as compressing each unbranched vertical path with no generator in the middle into one compressed node $$$p$$$, with shared generator set $$$G(p)$$$.
Handling next on the compressed tree
Now let's check how compression affects the fake edges next. When we merge nodes with the same generator set into one compressed node $$$p$$$, how do we handle next? Could merged nodes have conflicting next edges and break our algorithm?
Claim: There is never a conflict. Pick any character $$$c$$$ and all uncompressed nodes $$$u \in T_i$$$ inside the same compressed node $$$p$$$. Either all of them have $$$\text{next}(u, c) = \text{NULL}$$$, or all of their $$$\text{next}(u, c)$$$ pointers exist and point to target nodes $$$v = u \cdot c$$$ that belong to the same single compressed node $$$q$$$.
Proof: For the root $$$\lbrace\varepsilon\rbrace$$$ there is only one node, so there is nothing to conflict. Now take any compressed node $$$p$$$ of non-empty strings, any $$$u \in p$$$ (so $$$G(u) = G(p)$$$), and any character $$$c$$$. The string $$$v = u \cdot c$$$ appears in $$$T_i$$$ ending at index $$$j + 1 \le i$$$ if and only if some slice $$$S[l \dots j+1] = u \cdot c$$$ exists (meaning $$$P_{j+1} \in G(v)$$$). Since $$$u$$$ is non-empty, that is equivalent to $$$S[l \dots j] = u$$$ (with $$$1 \le j \lt i$$$) and $$$S[j+1] = c$$$, which means $$$P_j \in G(u) = G(p)$$$ and $$$S[j+1] = c$$$. Therefore:
The right side depends only on $$$p$$$ and $$$c$$$, not on which $$$u \in p$$$ we picked:
- If this set is empty, then $$$u \cdot c \notin T_i$$$ for every $$$u \in p$$$, so every $$$\text{next}(u, c) = \text{NULL}$$$.
- If this set is non-empty, then every $$$u \in p$$$ has $$$\text{next}(u, c) = v \in T_i$$$ with the same non-empty generator set $$$G(v)$$$ (and $$$|v| \ge 2$$$, so $$$v \ne \varepsilon$$$). By our grouping rule, all those targets $$$v$$$ belong to the same single compressed node $$$q$$$.
So we can merge all $$$\text{next}(u, c)$$$ pointers (for $$$u \in p$$$) into a single fake edge $$$\text{next}(p, c) = q$$$ (or NULL).
Let's see this on "abaca" (13 non-empty substrings). Figure 6 shows the full uncompressed Hasse tree of "abaca", and Figure 7 shows the compressed tree SAM("abaca"):

Figure 6: Uncompressed Hasse tree of "abaca".

Figure 7: Compressed tree SAM("abaca").
Look at Figures 6 and 7:
- In Figure 6, the green block
{"c", "ac", "bac", "abac"}has no branching and only one generator $$$P_4 = \text{"abac"}$$$ at the bottom ($$$G = \lbrace P_4\rbrace$$$). The orange block{"ca", "aca", "baca", "abaca"}has $$$G = \lbrace P_5\rbrace$$$. When we append'a', all 4 nodes in $$$G = \lbrace P_4\rbrace$$$ shoot purple arrows into the 4 matching nodes inside $$$G = \lbrace P_5\rbrace$$$. - After compression (Figure 7), 14 nodes shrink to 6 compressed nodes. The number in each box is the length of its longest string, black edges point to parents in the compressed tree, and purple arrows are
nextedges. All 4 parallel'a'arrows merge into one'a'edge.
Size, next update cost, and node attributes in the compressed tree
With this compression rule and next merging, both $$$O(n^2)$$$ problems drop to $$$O(n)$$$:
- Memory drops to $$$O(n)$$$ (at most $$$2n - 1$$$ nodes for $$$n \ge 2$$$): Every leaf holds some prefix $$$P_k$$$, so the compressed tree has $$$L \le n$$$ leaves. Every node in the tree is the root $$$\varepsilon$$$, a node holding some $$$P_k$$$ at its bottom (at most $$$n$$$ nodes), or a branching node with at least $$$2$$$ children (at most $$$L - 1$$$ nodes). When $$$L = 1$$$ ($$$S = a^n$$$), the tree is one chain of $$$n + 1 \le 2n - 1$$$ nodes; when $$$L \ge 2$$$, $$$S$$$ has at least $$$2$$$ distinct characters, so the root $$$\varepsilon$$$ itself branches and is already counted among the $$$L - 1 \le n - 1$$$ branching nodes, giving at most $$$n + (n - 1) = 2n - 1$$$ nodes (for $$$n = 1$$$ there are $$$2$$$ nodes).
nextupdates drop from $$$O(n^2)$$$ to $$$O(n)$$$: At step $$$i+1$$$ ($$$i \ge 1$$$), the suffixes $$$S[1 \dots i], \dots, S[w_i - 1 \dots i]$$$ (from the bottom $$$P_i$$$ up to just below $$$W_i$$$) are already compressed into $$$1$$$ nodelastwith nonextedges yet. So we do just $$$1$$$ assignment atlastand jump straight to the parent oflast(which contains $$$W_i$$$). From there up, we walk along the compressed version of the climb from $$$W_i$$$ to $$$S[w_{i+1} \dots i]$$$ on the uncompressed tree. Each compressed node merges at least $$$1$$$ uncompressed node, so we do at most $$$w_{i+1} - w_i$$$ assignments afterlast. Summing over all $$$n$$$ steps ($$$w_1 = 2$$$ and $$$w_n \le n + 1$$$), the total number of $$$\text{next}(p, c) \leftarrow \text{cur}$$$ assignments is:
- Attributes for each compressed node $$$p$$$: Instead of storing individual strings, each compressed node $$$p$$$ stores just three fields:
len[p]: length of the longest string in $$$p$$$ ($$$\text{len}[\varepsilon] = 0$$$).link[p]: parent of $$$p$$$ in the compressed tree ($$$\text{Par}$$$ after compression; $$$\text{link}[\varepsilon] = -1$$$).next[p]: table of fake edges $$$\text{next}(p, c)$$$ shared by the whole block $$$p$$$.
From len[p] and link[p], the strings in $$$p$$$ have consecutive lengths from $$$\text{len}[\text{link}[p]] + 1$$$ to $$$\text{len}[p]$$$ (so $$$p$$$ holds $$$\text{len}[p] - \text{len}[\text{link}[p]]$$$ distinct strings). Because every string in $$$p$$$ shares the same generator set $$$G(p)$$$, all queries from before (counting distinct substrings, counting occurrences, finding $$$\min / \max$$$ positions, $$$\text{LCA}$$$, and others) still work on the compressed tree.
3.6. Attaching new branches on the compressed tree
Compressing the tree brings back one old task: attaching the new branch onto the compressed tree.
When we add $$$c = S[i+1]$$$, we create a new node cur (length $$$i+1$$$). We set $$$p = \text{last}$$$, climb up link, and set $$$\text{next}(p, c) \leftarrow \text{cur}$$$ while that entry is empty. If we climb past the root $$$\varepsilon$$$, we set $$$\text{link}[\text{cur}] \leftarrow \varepsilon$$$ and we are done. Otherwise, we stop at the first node $$$p$$$ where $$$\text{next}(p, c) = q \ne \text{NULL}$$$.
Let's start from the same compressed tree SAM("abaca") (Figure 8, with next edges hidden to keep the tree clear) and check both possible cases:

Figure 8: Initial compressed tree SAM("abaca").
Case 1: "abaca" $$$\xrightarrow{+\,\texttt{b}}$$$ "abacab"
In the uncompressed tree (Figure 9), the new branch cur ({"cab", "acab", "bacab", "abacab"}) attaches right at the bottom "ab" of block $$$q = \lbrace\text{"b"}, \text{"ab"}\rbrace$$$. Block $$$q$$$ does not branch in the middle. So in the compressed result (Figure 10), $$$q$$$ stays intact and we just hang cur under $$$q$$$.

Figure 9: Case 1 (uncompressed) — cur attaches at the bottom of q.

Figure 10: Case 1 (compressed) — cur hangs directly under q.
Case 2: "abaca" $$$\xrightarrow{+\,\texttt{c}}$$$ "abacac"
Starting from the same tree in Figure 8, look at the uncompressed tree (Figure 11). The new branch cur ({"cac", "acac", "bacac", "abacac"}) attaches right in the middle of the 4-node block $$$q = \lbrace\text{"c"}, \text{"ac"}, \text{"bac"}, \text{"abac"}\rbrace$$$ at "ac" (red dashed line). That creates a branch in the middle and breaks our compression rule. So in the compressed result (Figure 12), we split $$$q$$$ into two nodes: clone = {"c", "ac"} (above the cut) and the updated $$$q$$$ = {"bac", "abac"} (below the cut). Then we hang both $$$q$$$ and cur under clone.

Figure 11: Case 2 (uncompressed) — cur attaches inside block q.

Figure 12: Case 2 (compressed) — q splits into clone and q.
Telling the two cases apart and handling them
Since $$$p$$$ is the first node with $$$\text{next}(p, c) = q$$$, the cut point $$$W_{i+1}$$$ has length $$$\text{len}[p] + 1$$$. We do not need to unpack $$$q$$$. We just compare $$$\text{len}[p] + 1$$$ with $$$\text{len}[q]$$$:
- If $$$\text{len}[p] + 1 = \text{len}[q]$$$ (Case 1): Set $$$\text{link}[\text{cur}] \leftarrow q$$$.
- If $$$\text{len}[p] + 1 \lt \text{len}[q]$$$ (Case 2): The cut lands in the middle of block $$$q$$$, splitting $$$q$$$ in two as shown in Figure 13:

Figure 13: Splitting block q into clone in 4 steps.
- Create
clone(top half of $$$q$$$): Set $$$\text{len}[\text{clone}] \leftarrow \text{len}[p] + 1$$$ and $$$\text{link}[\text{clone}] \leftarrow \text{link}[q]$$$. - Attach both children to
clone: Set $$$\text{link}[q] \leftarrow \text{clone}$$$ and $$$\text{link}[\text{cur}] \leftarrow \text{clone}$$$. - Outgoing edges of
clone: Copy $$$\text{next}[\text{clone}] \leftarrow \text{next}[q]$$$ (splitting $$$q$$$ after the climb fromlastonly adds $$$P_{i+1}$$$ to the generator set ofclone, and since $$$P_{i+1}$$$ ends at index $$$i + 1$$$, it creates no outgoing edge past $$$i + 1$$$). - Incoming edges to
clone: Keep climbing from $$$p$$$ vialink. While $$$\text{next}(p, c) = q$$$, redirect it toclone(every string incloneis a suffix of $$$W_{i+1}$$$, so dropping the final $$$c$$$ always gives a suffix of the longest string in $$$p$$$, meaning $$$p$$$ or one of its ancestors; all other nodes pointing to $$$q$$$ still land in the bottom half $$$q$$$).
Finally, update $$$\text{last} \leftarrow \text{cur}$$$ for the next step.
4. Suffix Automaton code
struct State {
int len = 0, link = -1;
map<char, int> next; // or int next[26] for a small alphabet
};
vector<State> st(1); // st[0] is the root epsilon: len = 0, link = -1
int last = 0; // Compressed node containing the previous prefix P_i
void extend(char c) {
// 1. Create a new compressed node cur for the new chain u_1 ... u_{k*-1}
int cur = st.size();
st.push_back(State{st[last].len + 1, 0, {}});
// 2. Climb from last: set next(p, c) = cur while it is empty
int p = last;
while (p != -1 && !st[p].next.count(c)) {
st[p].next[c] = cur;
p = st[p].link;
}
if (p == -1) {
// Climbed past the root epsilon: character c is new
st[cur].link = 0;
} else {
int q = st[p].next[c];
if (st[p].len + 1 == st[q].len) {
// Case 1: Cut point is at the bottom of block q -> no split
st[cur].link = q;
} else {
// Case 2: Cut point is inside block q -> split and create clone
int clone = st.size();
st.push_back(st[q]); // Copy next[q] and link[q]
st[clone].len = st[p].len + 1; // Cut at length len[p] + 1
// Redirect c-edges of p and its ancestors from q to clone
while (p != -1 && st[p].next[c] == q) {
st[p].next[c] = clone;
p = st[p].link;
}
// Hang both q and cur under clone
st[q].link = st[cur].link = clone;
}
}
last = cur; // Update last for the next step
}
Complexity
- Number of nodes (states): As shown when compressing the tree, $$$|V_n| \le 2n - 1 = O(n)$$$ (for $$$n \ge 2$$$).
- Number of
nextedges: - Let $$$\deg^+(v)$$$ be the number of outgoing fake edges
nextfrom node $$$v \in T_i$$$ (the uncompressed tree for $$$S[1 \dots i]$$$). Consider the sum:
- At step $$$1$$$, only the root $$$\varepsilon$$$ goes from $$$\deg^+ = 0$$$ to $$$1$$$, so $$$\Delta_1 = 0$$$ ($$$w_1 = 2$$$). At step $$$i + 1$$$ ($$$1 \le i \le n - 1$$$), all new nodes have $$$\deg^+ = 0$$$, no edge for $$$a \ne c = S[i+1]$$$ changes, and only the chain $$$v_1, \dots, v_{w_{i+1} - 1}$$$ ($$$v_k = S[k \dots i]$$$, with $$$v_{i+1} = \varepsilon$$$) increases $$$\deg^+$$$ by $$$1$$$. Split this chain at $$$w_i$$$ ($$$w_i \le w_{i+1}$$$):
- First part ($$$1 \le k \le w_i - 1$$$): These nodes were just created at step $$$i$$$, so they have $$$\deg^+(v_k) = 0$$$. Adding the $$$c$$$-edge moves $$$\deg^+$$$ from $$$0$$$ to $$$1$$$, which adds $$$0$$$ to $$$\Delta$$$.
- Second part ($$$w_i \le k \le w_{i+1} - 1$$$): These $$$w_{i+1} - w_i$$$ nodes all already have $$$\deg^+(v_k) \ge 1$$$ in $$$T_i$$$. (If $$$k = i + 1$$$, then $$$v_k = \varepsilon$$$ already has an edge on $$$S[1]$$$. If $$$k \le i$$$, then $$$v_k$$$ appeared earlier at $$$S[l \dots r]$$$ with $$$r \lt i$$$, so it already has an edge on $$$S[r+1]$$$.) So each node here adds $$$1$$$ to $$$\Delta$$$.
- Thus $$$\Delta_{i+1} - \Delta_i = w_{i+1} - w_i$$$. Summing from $$$1$$$ to $$$n - 1$$$ gives $$$\Delta_n = w_n - w_1$$$.
- Every uncompressed node $$$v$$$ inside the same compressed node $$$p \in V_n$$$ (in the compressed tree) has the same out-degree $$$d^+(p) = \deg^+(v)$$$. Since compressed nodes partition $$$T_n$$$ into disjoint blocks, $$$\sum_{p \in V_n,\; d^+(p) \ge 1} (d^+(p) - 1) \le \Delta_n = w_n - w_1$$$. Also, the node
lastcontaining the full string $$$S$$$ has $$$d^+ = 0$$$, so at most $$$|V_n| - 1$$$ nodes have $$$d^+(p) \ge 1$$$. Adding back $$$1$$$ per node gives:
- For $$$n \ge 3$$$ ($$$w_1 = 2$$$ and $$$|V_m| \le 2m - 1$$$ for $$$m \ge 2$$$), check both cases at the last step $$$n$$$: if $$$S[n]$$$ is new, then $$$w_n = n + 1$$$, and step $$$n$$$ climbs past $$$\varepsilon$$$ without creating a
clone, so $$$|V_n| = |V_{n-1}| + 1 \le 2n - 2$$$ and $$$|E| \le (2n - 3) + (n - 1) = 3n - 4$$$. If $$$S[n]$$$ already appeared earlier, then $$$w_n \le n$$$ and $$$|V_n| \le 2n - 1$$$, giving $$$|E| \le (2n - 2) + (n - 2) = 3n - 4$$$ as well. Sincenextedges are never deleted, withstd::mapevery edge copied into acloneadds $$$1$$$ to $$$|E|$$$. So the total cost ofst.push_back(st[q])over the whole run is also $$$O(n)$$$. - Build time:
- First
whileloop (assigning edges tocur): This is the exact $$$\text{next}(p, c) \leftarrow \text{cur}$$$ update we already bounded on the compressed tree, taking at most $$$2n - 1 = O(n)$$$ total steps. - Second
whileloop (redirecting edges toclone): Let $$$\text{depth}(v)$$$ be the number oflinkedges from compressed node $$$v$$$ up to the root $$$\varepsilon$$$ ($$$\text{depth}(\varepsilon) = 0$$$).- For every fake edge $$$\text{next}(u, c) = q$$$, we have $$$\text{depth}(q) \le \text{depth}(u) + 1$$$. Take a string $$$x \in u$$$ so that $$$x \cdot c$$$ appears as some slice $$$S[l \dots r+1] \in q$$$ (with $$$x = S[l \dots r]$$$, or $$$x = \varepsilon$$$ when $$$l = r + 1$$$). Every non-root node on the path from $$$q$$$ to $$$\varepsilon$$$ holds a non-empty suffix $$$S[k \dots r+1] = S[k \dots r] \cdot c$$$ ($$$l \le k \le r + 1$$$, where $$$S[r+1 \dots r] = \varepsilon$$$). Every $$$S[k \dots r]$$$ lies on the path from $$$u$$$ to $$$\varepsilon$$$, which has $$$\text{depth}(u) + 1$$$ compressed nodes. Each compressed node $$$w$$$ on that path gives at most $$$1$$$ target $$$\text{next}(w, c)$$$, so the path from $$$q$$$ to $$$\varepsilon$$$ has at most $$$\text{depth}(u) + 1$$$ non-root nodes.
- Set $$$D_i = \text{depth}(\text{last}_i)$$$ ($$$D_0 = 0$$$, $$$D_i \ge 0$$$). At step $$$i+1$$$, let $$$k_1 \ge 1$$$ and $$$k_2 \ge 0$$$ be the iteration counts of the first and second
whileloops: - If
p == -1($$$k_2 = 0$$$):link[cur] = 0, so $$$D_{i+1} = 1 \le D_i + 1$$$. - If Case 1 ($$$k_2 = 0$$$): $$$\text{depth}(p) = D_i - k_1 \le D_i - 1$$$, so $$$D_{i+1} = \text{depth}(q) + 1 \le \text{depth}(p) + 2 \le D_i + 1$$$.
- If Case 2 ($$$k_2 \ge 1$$$): on the tree right before splitting $$$q$$$, the last node $$$u$$$ redirected to
clonehad $$$\text{next}(u, c) = q$$$ and $$$\text{depth}(u) = D_i - k_1 - (k_2 - 1) \le D_i - k_2$$$ (since $$$k_1 \ge 1$$$). Becauseclonecopieslink[q], it keeps that old depth of $$$q$$$, so $$$D_{i+1} = \text{depth}_{\text{old}}(q) + 1 \le \text{depth}(u) + 2 \le D_i - k_2 + 2$$$. - In every case, $$$k_2 \le D_i - D_{i+1} + 2$$$. Summing over all $$$n$$$ steps:
So the whole algorithm runs in $$$O(n)$$$ time (for a fixed-size alphabet) or $$$O(n \log |\Sigma|)$$$ time (with std::map), using $$$O(n)$$$ memory.








You have made a good FirstImpression!
Od_Ali the topic that you asked for )
orz, but I'm not sure I'll understand all of this
Fine
I hope this helps you.
step by step demo and you can use custom input and see how it works https://antinloop.com/algorithms/suffix-automaton/demo
An exercise on the extend function to help you understand what is going on https://antinloop.com/games/suffix-automaton?mode=extend
An exercise on the query function https://antinloop.com/games/suffix-automaton?mode=query
Orz, this view of SAM is really helpful. Great post!