<p>Apologies if my answer seems redundant, but I implemented Ukkonen's algorithm recently, and found myself struggling with it for days; I had to read through multiple papers on the subject to understand the why and how of some core aspects of the algorithm.</p>

<p>I found the 'rules' approach of previous answers unhelpful for understanding the underlying <em>reasons</em>, so I've written everything below focusing solely on the pragmatics. If you've struggled with following other explanations, just like I did, perhaps my supplemental explanation will make it 'click' for you.</p>

<p>I published my C# implementation here: <a href="https://github.com/baratgabor/SuffixTree" rel="noreferrer">https://github.com/baratgabor/SuffixTree</a></p>

<p><em>Please note that I'm not an expert on this subject, so the following sections may contain inaccuracies (or worse). If you encounter any, feel free to edit.</em></p>

<h2>Prerequisites</h2>

<p>The starting point of the following explanation assumes you're familiar with the content and use of suffix trees, and the characteristics of Ukkonen's algorithm, e.g. how you're extending the suffix tree character by character, from start to end. Basically, I assume you've read some of the other explanations already. </p>

<p>(However, I did have to add some basic narrative for the flow, so the beginning might indeed feel redundant.)</p>

<p>The most interesting part is the <em>explanation on the difference between using suffix links and rescanning from the root</em>. This is what gave me a lot of bugs and headaches in my implementation.</p>

<h2>Open-ended leaf nodes and their limitations</h2>

<p>I'm sure you already know that the most fundamental 'trick' is to realize we can just leave the end of the suffixes 'open', i.e. referencing the current length of the string instead of setting the end to a static value. This way when we add additional characters, those characters will be implicitly added to all suffix labels, without having to visit and update all of them.</p>

<p>But this open ending of suffixes – for obvious reasons – works only for nodes that represent the end of the string, i.e. the leaf nodes in the tree structure. The branching operations we execute on the tree (the addition of new branch nodes and leaf nodes) won't propagate automatically everywhere they need to.</p>

<p><em>It's probably elementary, and wouldn't require mention, that repeated substrings don't appear explicitly in the tree, since the tree already contains these by virtue of them being repetitions; however, when the repetitive substring ends by encountering a non-repeating character, we need to create a branching at that point to represent the divergence from that point onwards.</em></p>

<p>For example in case of the string <em>'ABCXABCY'</em> (see below), a branching to <em>X</em> and <em>Y</em> needs to be added to three different suffixes, <em>ABC</em>, <em>BC</em> and <em>C</em>; otherwise it wouldn't be a valid suffix tree, and we couldn't find all substrings of the string by matching characters from the root downwards.</p>

<p>Once again, to emphasize – <em>any</em> operation we execute on a suffix in the tree needs to be reflected by its consecutive suffixes as well (e.g. ABC > BC > C), otherwise they simply cease to be valid suffixes.</p>

<p><a href="https://i.stack.imgur.com/pyaNY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pyaNY.png" alt="Repeating branching in suffixes"></a></p>

<p>But even if we accept that we have to do these manual updates, how do we know how many suffixes need to be updated? Since, when we add the repeated character <em>A</em> (and the rest of the repeated characters in succession), we have no idea yet when/where do we need to split the suffix into two branches. The need to split is ascertained only when we encounter the first non-repeating character, in this case <em>Y</em> (instead of the <em>X</em> that already exists in the tree).</p>

<p>What we can do is to match the longest repeated string we can, and count how many of its suffixes we need to update later. This is what <em>'remainder'</em> stands for.</p>

<h2>The concept of 'remainder' and 'rescanning'</h2>

<p>The variable <code>remainder</code> tells us how many repeated characters we added implicitly, without branching; i.e. how many suffixes we need to visit to repeat the branching operation once we found the first character that we cannot match. This essentially equals to how many characters 'deep' we are in the tree from its root.</p>

<p>So, staying with the previous example of the string <em>ABCXABCY</em>, we match the repeated <em>ABC</em> part 'implicitly', incrementing <code>remainder</code> each time, which results in remainder of 3. Then we encounter the non-repeating character <em>'Y'</em>. Here we split the previously added <em>ABCX</em> into <em>ABC</em>-><em>X</em> and <em>ABC</em>-><em>Y</em>. Then we decrement <code>remainder</code> from 3 to 2, because we already took care of the <em>ABC</em> branching. Now we repeat the operation by matching the last 2 characters – <em>BC</em> – from the root to reach the point where we need to split, and we split <em>BCX</em> too into <em>BC</em>-><em>X</em> and <em>BC</em>-><em>Y</em>. Again, we decrement <code>remainder</code> to 1, and repeat the operation; until the <code>remainder</code> is 0. Lastly, we need to add the current character (<em>Y</em>) itself to the root as well.</p>

<p>This operation, following the consecutive suffixes from the root simply to reach the point where we need to do an operation is what's called <em>'rescanning'</em> in Ukkonen's algorithm, and typically this is the most expensive part of the algorithm. Imagine a longer string where you need to 'rescan' long substrings, across many dozens of nodes (we'll discuss this later), potentially thousands of times.</p>

<p>As a solution, we introduce what we call <em>'suffix links'</em>.</p>

<h2>The concept of 'suffix links'</h2>

<p>Suffix links basically point to the positions we'd normally have to <em>'rescan'</em> to, so instead of the expensive rescan operation we can simply jump to the linked position, do our work, jump to the next linked position, and repeat – until there are no more positions to update.</p>

<p>Of course one big question is how to add these links. The existing answer is that we can add the links when we insert new branch nodes, utilizing the fact that, in each extension of the tree, the branch nodes are naturally created one after another in the exact order we'd need to link them together. Though, we have to link from the last created branch node (the longest suffix) to the previously created one, so we need to cache the last we create, link that to the next one we create, and cache the newly created one.</p>

<p>One consequence is that we actually often don't have suffix links to follow, because the given branch node was just created. In these cases we have to still fall back to the aforementioned <em>'rescanning'</em> from root. This is why, after an insertion, you're instructed to either use the suffix link, or jump to root.</p>

<p>(Or alternatively, if you're storing parent pointers in the nodes, you can try to follow the parents, check if they have a link, and use that. I found that this is very rarely mentioned, but <em>the suffix link usage is not set in stones.</em> There are multiple possible approaches, and if you understand the underlying mechanism you can implement one that fits your needs the best.)</p>

<h2>The concept of 'active point'</h2>

<p>So far we discussed multiple efficient tools for building the tree, and vaguely referred to traversing over multiple edges and nodes, but haven't yet explored the corresponding consequences and complexities.</p>

<p>The previously explained concept of <em>'remainder'</em> is useful for keeping track where we are in the tree, but we have to realize it doesn't store enough information.</p>

<p>Firstly, we always reside on a specific edge of a node, so we need to store the edge information. We shall call this <em>'active edge'</em>.</p>

<p>Secondly, even after adding the edge information, we still have no way to identify a position that is farther down in the tree, and not directly connected to the <em>root</em> node. So we need to store the node as well. Let's call this <em>'active node'</em>.</p>

<p>Lastly, we can notice that the <em>'remainder'</em> is inadequate to identify a position on an edge that is not directly connected to root, because <em>'remainder'</em> is the length of the entire route; and we probably don't want to bother with remembering and subtracting the length of the previous edges. So we need a representation that is essentially the <em>remainder on the current edge</em>. This is what we call <em>'active length'</em>.</p>

<p>This leads to what we call <em>'active point'</em> – a package of three variables that contain all the information we need to maintain about our position in the tree:</p>

<p><code>Active Point = (Active Node, Active Edge, Active Length)</code></p>

<p>You can observe on the following image how the matched route of <em>ABCABD</em> consists of 2 characters on the edge <em>AB</em> (from <em>root</em>), plus 4 characters on the edge <em>CABDABCABD</em> (from node 4) – resulting in a <em>'remainder'</em> of 6 characters. So, our current position can be identified as <em>Active Node 4, Active Edge C, Active Length 4</em>.</p>

<p><a href="https://i.stack.imgur.com/FdbDQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FdbDQ.png" alt="Remainder and Active Point"></a></p>

<p>Another important role of the <em>'active point'</em> is that it provides an abstraction layer for our algorithm, meaning that parts of our algorithm can do their work on the <em>'active point'</em>, irrespective of whether that active point is in the root or anywhere else. This makes it easy to implement the use of suffix links in our algorithm in a clean and straight-forward way.</p>

<h2>Differences of rescanning vs using suffix links</h2>

<p>Now, the tricky part, something that – in my experience – can cause plenty of bugs and headaches, and is poorly explained in most sources, is the difference in processing the suffix link cases vs the rescan cases.</p>

<p>Consider the following example of the string <em>'AAAABAAAABAAC'</em>:</p>

<p><a href="https://i.stack.imgur.com/YdSPZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YdSPZ.png" alt="Remainder across multiple edges"></a></p>

<p>You can observe above how the <em>'remainder'</em> of 7 corresponds to the total sum of characters from root, while <em>'active length'</em> of 4 corresponds to the sum of matched characters from the active edge of the active node.</p>

<p>Now, after executing a branching operation at the active point, our active node might or might not contain a suffix link.</p>

<p><strong>If a suffix link is present:</strong> We only need to process the <em>'active length'</em> portion. The <em>'remainder'</em> is irrelevant, because <em>the node where we jump to via the suffix link already encodes the correct 'remainder' implicitly</em>, simply by virtue of being in the tree where it is.</p>

<p><strong>If a suffix link is NOT present:</strong> We need to <em>'rescan'</em> from zero/root, which means processing the whole suffix from the beginning. To this end we have to use the whole <em>'remainder'</em> as the basis of rescanning.</p>

<h2>Example comparison of processing with and without a suffix link</h2>

<p>Consider what happens at the next step of the example above. Let's compare how to achieve the same result – i.e. moving to the next suffix to process – with and without a suffix link.</p>

<h3><strong>Using <em>'suffix link'</em></strong></h3>

<p><a href="https://i.stack.imgur.com/OXxrn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OXxrn.png" alt="Reaching consecutive suffixes via suffix links"></a></p>

<p>Notice that if we use a suffix link, we are automatically 'at the right place'. Which is often not strictly true due to the fact that the <em>'active length'</em> can be 'incompatible' with the new position.</p>

<p>In the case above, since the <em>'active length'</em> is 4, we're working with the suffix '<em>ABAA'</em>, starting at the linked Node 4. But after finding the edge that corresponds to the first character of the suffix (<em>'A'</em>), we notice that our <em>'active length'</em> overflows this edge by 3 characters. So we jump over the full edge, to the next node, and decrement <em>'active length'</em> by the characters we consumed with the jump.</p>

<p>Then, after we found the next edge <em>'B'</em>, corresponding to the decremented suffix <em>'BAA</em>', we finally note that the edge length is larger than the remaining <em>'active length'</em> of 3, which means we found the right place.</p>

<p><em>Please note that it seems this operation is usually not referred to as 'rescanning', even though to me it seems it's the direct equivalent of rescanning, just with a shortened length and a non-root starting point.</em></p>

<h3><strong>Using <em>'rescan'</em></strong></h3>

<p><a href="https://i.stack.imgur.com/2L6U1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2L6U1.png" alt="Reaching consecutive suffixes via rescanning"></a></p>

<p>Notice that if we use a traditional 'rescan' operation (here pretending we didn't have a suffix link), we start at the top of the tree, at root, and we have to work our way down again to the right place, following along the entire length of the current suffix.</p>

<p>The length of this suffix is the <em>'remainder'</em> we discussed before. We have to consume the entirety of this remainder, until it reaches zero. This might (and often does) include jumping through multiple nodes, at each jump decreasing the remainder by the length of the edge we jumped through. Then finally, we reach an edge that is longer than our remaining <em>'remainder'</em>; here we set the active edge to the given edge, set <em>'active length'</em> to remaining <em>'remainder</em>', and we're done.</p>

<p>Note, however, that the actual <em>'remainder'</em> variable needs to be preserved, and only decremented after each node insertion. So what I described above assumed using a separate variable initialized to <em>'remainder'</em>.</p>

<p><strong>Notes on suffix links &amp; rescans</strong></p>

<p>1) Notice that both methods lead to the same result. Suffix link jumping is, however, significantly faster in most cases; that's the whole rationale behind suffix links.</p>

<p>2) The actual algorithmic implementations don't need to differ. As I mentioned above, even in the case of using the suffix link, the <em>'active length'</em> is often not compatible with the linked position, since that branch of the tree might contain additional branching. So essentially you just have to use <em>'active length'</em> instead of <em>'remainder'</em>, and execute the same rescanning logic until you find an edge that is shorter than your remaining suffix length.</p>

<p>3) One important remark pertaining to performance is that there is no need to check each and every character during rescanning. Due to the way a valid suffix tree is built, we can safely assume that the characters match. So you're mostly counting the lengths, and the only need for character equivalence checking arises when we jump to a new edge, since edges are identified by their first character (which is always unique in the context of a given node). This means that 'rescanning' logic is different than full string matching logic (i.e. searching for a substring in the tree).</p>

<p>4) The original suffix linking described here is just <em>one of the possible approaches</em>. For example <a href="https://arxiv.org/pdf/1403.0457.pdf" rel="noreferrer">NJ Larsson et al.</a> names this approach as <em>Node-Oriented Top-Down</em>, and compares it to <em>Node-Oriented Bottom-Up</em> and two <em>Edge-Oriented</em> varieties. The different approaches have different typical and worst case performances, requirements, limitations, etc., but it generally seems that <em>Edge-Oriented</em> approaches are an overall improvement to the original.</p>
Ukkonen's suffix tree algorithm in plain English
<p>I feel a bit thick at this point. I've spent days trying to fully wrap my head around suffix tree construction, but because I don't have a mathematical background, many of the explanations elude me as they start to make excessive use of mathematical symbology. The closest to a good explanation that I've found is <em><a href="http://marknelson.us/1996/08/01/suffix-trees/" rel="noreferrer">Fast String Searching With Suffix Trees</a></em>, but he glosses over various points and some aspects of the algorithm remain unclear.</p>

<p>A step-by-step explanation of this algorithm here on Stack&nbsp;Overflow would be invaluable for many others besides me, I'm sure.</p>

<p>For reference, here's Ukkonen's paper on the algorithm: <a href="http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf" rel="noreferrer">http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf</a></p>

<p>My basic understanding, so far:</p>

<ul>
<li>I need to iterate through each prefix P of a given string T</li>
<li>I need to iterate through each suffix S in prefix P and add that to tree</li>
<li>To add suffix S to the tree, I need to iterate through each character in S, with the iterations consisting of either walking down an existing branch that starts with the same set of characters C in S and potentially splitting an edge into descendent nodes when I reach a differing character in the suffix, OR if there was no matching edge to walk down. When no matching edge is found to walk down for C, a new leaf edge is created for C.</li>
</ul>

<p>The basic algorithm appears to be O(n<sup>2</sup>), as is pointed out in most explanations, as we need to step through all of the prefixes, then we need to step through each of the suffixes for each prefix. Ukkonen's algorithm is apparently unique because of the suffix pointer technique he uses, though I think <em>that</em> is what I'm having trouble understanding.</p>

<p>I'm also having trouble understanding:</p>

<ul>
<li>exactly when and how the "active point" is assigned, used and changed</li>
<li>what is going on with the canonization aspect of the algorithm</li>
<li>Why the implementations I've seen need to "fix" bounding variables that they are using</li>
</ul>

<hr>

<p>Here is the completed <strong>C#</strong> source code. It not only works correctly, but supports automatic canonization and renders a nicer looking text graph of the output. Source code and sample output is at:</p>

<blockquote>
  <p><strong><a href="https://gist.github.com/2373868" rel="noreferrer">https://gist.github.com/2373868</a></strong></p>
</blockquote>

<hr>

<p><strong>Update 2017-11-04</strong></p>

<p>After many years I've found a new use for suffix trees, and have implemented the algorithm in <strong>JavaScript</strong>. Gist is below. It should be bug-free. Dump it into a js file, <code>npm install chalk</code> from the same location, and then run with node.js to see some colourful output. There's a stripped down version in the same Gist, without any of the debugging code.</p>

<blockquote>
  <p><strong><a href="https://gist.github.com/axefrog/c347bf0f5e0723cbd09b1aaed6ec6fc6" rel="noreferrer">https://gist.github.com/axefrog/c347bf0f5e0723cbd09b1aaed6ec6fc6</a></strong></p>
</blockquote>