{"id":292,"date":"2026-11-13T12:37:10","date_gmt":"2026-11-13T04:37:10","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-ukkonen-builds-a-suffix-tree-online\/"},"modified":"2026-11-13T21:58:41","modified_gmt":"2026-11-13T13:58:41","slug":"how-ukkonen-builds-a-suffix-tree-online","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-ukkonen-builds-a-suffix-tree-online\/","title":{"rendered":"How Ukkonen builds a suffix tree online"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Ukkonen&#8217;s algorithm<\/strong> builds a <strong>suffix tree<\/strong>, the compacted trie of all suffixes, online in <strong>O(n)<\/strong> time for a fixed alphabet. It processes the string left to right and keeps an active point, the place where the next character must be inserted for every suffix that has not yet branched. <strong>Suffix links<\/strong> jump from a node to the node that represents its path with the first character removed. Edge labels are stored as pairs of indices into the text, so the tree occupies <strong>O(n)<\/strong> memory rather than a copy of every suffix.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A suffix tree answers exact pattern search in O(m) time and stores n suffixes without writing n\u00b2 characters. The naive construction inserts each suffix into a trie and compresses, which is quadratic. Ukkonen&#8217;s online pass inserts the next character into every current suffix by exploiting the fact that those insertion points form a chain connected by suffix links.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The active point is a triple: a node, an edge, and a length along that edge. Most suffixes do not need a new node on a given character. They already continue along an edge, and the active point just slides forward. A new branch is created only when the character misses.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">For an alphabet treated as constant, the algorithm runs in O(n) time and produces a tree with at most 2n nodes. Edge labels are substrings of the original text, represented by a start index and an end index. Leaf edges often share an open end index that means &#8220;the current end of the text,&#8221; which is how the online extension of every leaf happens in constant time per character. Extra memory is O(n).<\/p>\n\n\n<p class=\"wp-block-paragraph\">A sentinel character that appears nowhere else is appended so that every suffix ends at a leaf and no suffix is a prefix of another. Without the sentinel, some suffixes end in the middle of an edge and the tree is still definable, and many construction writeups assume the sentinel. Pattern search walks from the root by the pattern characters in O(m). Longest repeated substring is the deepest internal node.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Append a sentinel that is smaller than every alphabet character and appears once.<\/li>\n<li>Maintain the active point and a remainder, the number of suffixes that still need the current character.<\/li>\n<li>For each new text position, increment the remainder and the global end index so every open leaf edge grows by one.<\/li>\n<li>While the remainder is positive and the active point has no edge for the new character, create a leaf, create an internal node if the active point is in the middle of an edge, and follow or create a suffix link to move the active point to the next shorter suffix.<\/li>\n<li>If the character already continues from the active point, advance the active point and stop the remainder loop for this character. The rest of the suffixes will see the same continuation.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear bound needs index pairs on the edges and suffix links. Copying the spelled-out label onto each edge returns the memory to quadratic. A suffix array plus an LCP array represents the same combinatorial object more compactly and is often what a program should build instead. Ukkonen&#8217;s tree is the explicit compacted trie.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when each edge stores its own character copy<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Copy the substring into the edge label<\/td>\n<td>The tree is combinatorially right and the memory is O(n\u00b2). Index pairs into the original text are the linear representation.<\/td>\n<\/tr>\n<tr>\n<td>Omit suffix links and walk from the root for every suffix<\/td>\n<td>Each character can then cost linear time. The links are the reason the active point moves in amortized constant time.<\/td>\n<\/tr>\n<tr>\n<td>Forget the sentinel<\/td>\n<td>A suffix that is a prefix of another ends on an edge, and algorithms that assume every suffix is a leaf, including some longest-common-substring walks, miss it.<\/td>\n<\/tr>\n<tr>\n<td>Quote O(n) for a large integer alphabet without a map caveat<\/td>\n<td>Child lookup has to be constant time for the textbook bound. A balanced map at each node adds a log factor in the alphabet.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">The compact sorted list of the same suffixes is a suffix array, built by prefix doubling or SA-IS, with Kasai&#8217;s LCP array beside it. Ukkonen&#8217;s algorithm is the online suffix-tree construction.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment appends one character at a time, grows every open leaf through a shared end index, and follows suffix links for the active point. Every suffix of <code>banana$<\/code> is found in the tree. It prints <code>7<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def build(text):\n    nodes = [{}]\n    links = [0]\n    end = [0]\n    active_node = active_edge = active_length = 0\n    remainder = 0\n\n    def edge_len(start, stop):\n        return (end[0] if stop is None else stop) - start\n\n    for i in range(len(text)):\n        end[0] = i + 1\n        remainder += 1\n        last = None\n        while remainder:\n            if active_length == 0:\n                active_edge = i\n            char = text[active_edge]\n            if char not in nodes[active_node]:\n                leaf = len(nodes)\n                nodes.append({})\n                links.append(0)\n                nodes[active_node][char] = [active_edge, None, leaf]\n                if last is not None:\n                    links[last] = active_node\n                    last = None\n            else:\n                start, stop, dest = nodes[active_node][char]\n                length = edge_len(start, stop)\n                if active_length &gt;= length:\n                    active_edge += length\n                    active_length -= length\n                    active_node = dest\n                    continue\n                if text[start + active_length] == text[i]:\n                    active_length += 1\n                    if last is not None:\n                        links[last] = active_node\n                    break\n                split = len(nodes)\n                nodes.append({})\n                links.append(0)\n                nodes[active_node][char] = [start, start + active_length, split]\n                leaf = len(nodes)\n                nodes.append({})\n                links.append(0)\n                nodes[split][text[i]] = [i, None, leaf]\n                nodes[split][text[start + active_length]] = [start + active_length, stop, dest]\n                if last is not None:\n                    links[last] = split\n                last = split\n            remainder -= 1\n            if active_node == 0 and active_length:\n                active_length -= 1\n                active_edge = i - remainder + 1\n            elif active_node:\n                active_node = links[active_node]\n    return nodes, end\n\ndef has_suffix(nodes, end, text, suffix):\n    node = 0\n    i = 0\n    while i &lt; len(suffix):\n        char = suffix[i]\n        if char not in nodes[node]:\n            return False\n        start, stop, dest = nodes[node][char]\n        label = text[start:end[0] if stop is None else stop]\n        if suffix[i:i + len(label)] != label[: len(suffix) - i]:\n            return False\n        i += len(label)\n        node = dest\n    return True\n\ntext = &quot;banana$&quot;\nnodes, end = build(text)\nassert all(has_suffix(nodes, end, text, text[i:]) for i in range(len(text)))\nprint(len(text))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Ukkonen&#8217;s algorithm builds a suffix tree online in linear time. Genome search used suffix trees built this way; many aligners now use a suffix array or an <strong>FM-index<\/strong> instead. The tree and the array store the same suffixes.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop a suffix tree when a suffix array answers the query you have. The array is smaller and easier to get right. Keep Ukkonen&#8217;s construction when the explicit tree, the suffix links, or the online extension is the object you need.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Ukkonen&#8217;s algorithm returns the active point, the suffix links, and the index-pair edge labels that keep the tree linear. <strong>Ukkonen&#8217;s algorithm builds a suffix tree online in linear time by extending an active point along suffix links and storing edge labels as indices into the text.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Ukkonen&#8217;s algorithm builds a suffix tree, the compacted trie of all suffixes, online in O(n) time for a fixed alphabet. It processes the string left to right and keeps an active point, the place where the next character must be inserted for every suffix that has not&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,38],"tags":[],"class_list":["post-292","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-strings"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/292","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=292"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/292\/revisions"}],"predecessor-version":[{"id":691,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/292\/revisions\/691"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=292"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}