{"id":207,"date":"2026-11-13T12:34:35","date_gmt":"2026-11-13T04:34:35","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-kasai-builds-the-lcp-array-from-a-suffix-array\/"},"modified":"2026-11-13T21:52:46","modified_gmt":"2026-11-13T13:52:46","slug":"how-kasai-builds-the-lcp-array-from-a-suffix-array","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-kasai-builds-the-lcp-array-from-a-suffix-array\/","title":{"rendered":"How Kasai builds the LCP array from a suffix array"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Kasai&#8217;s algorithm<\/strong> builds the <strong>LCP array<\/strong> of a string from its suffix array in <strong>O(n)<\/strong> time. LCP[i] is the length of the longest common prefix of the suffixes that are adjacent in sorted order, SA[i\u22121] and SA[i]. The algorithm walks the suffixes in text order and uses the inequality LCP[rank[i]] \u2265 LCP[rank[i\u22121]] \u2212 1, so the comparison window only moves forward. The total number of character comparisons is linear.<\/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\">The suffix array sorts suffixes and does not say how much neighboring suffixes share. Almost every interesting query, longest repeated substring, distinct substring counts, pattern search with fewer comparisons, needs that shared length. Computing each LCP by a fresh scan is O(n\u00b2) on a repetitive string.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Kasai&#8217;s inequality says the suffix that starts one position after a suffix with a long LCP against its sorted neighbor still has a long LCP against its own sorted neighbor, off by at most one. The window of verified characters therefore slides.<\/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\">Given SA and its inverse rank, the algorithm fills LCP in O(n) character comparisons and O(n) extra memory. LCP[i] for i from 1 to n\u22121 is the common-prefix length of SA[i\u22121] and SA[i]. LCP[0] is unused or zero. The longest value in the array is the length of the longest repeated substring, achieved by some pair of adjacent suffixes in sorted order, because a non-adjacent pair&#8217;s common prefix cannot exceed the minimum LCP between them.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The inequality is a lower bound the algorithm uses to skip comparisons. It is not a license to skip the verification of the remaining characters. A wrong inverse rank, off by one, compares unrelated suffixes and the values are garbage while still looking like an array of integers.<\/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>Build the inverse rank so rank[SA[i]] = i. The suffix that starts at position p sits at sorted index rank[p].<\/li>\n<li>Set k = 0. This k is the length already known to match for the current text position.<\/li>\n<li>For text position i from 0 to n\u22121, if rank[i] is 0, set k = 0 and continue. Otherwise let j = SA[rank[i]\u22121], the suffix just above i in sorted order.<\/li>\n<li>While both suffixes still have characters and s[i+k] equals s[j+k], increment k. Store LCP[rank[i]] = k.<\/li>\n<li>If k &gt; 0, decrement k once before the next i. The next text position inherits k\u22121 matched characters.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear bound needs the already built suffix array and its inverse. It does not build the suffix array. Prefix doubling or SA-IS does that. Range-minimum queries on the LCP array answer the longest common prefix of any two suffixes, not only adjacent ones, and that structure is a sparse table or a segment tree on top of Kasai&#8217;s output.<\/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 the inherited length is not reduced by one<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Carry k unchanged to the next text position<\/td>\n<td>The next suffix dropped the first character. Keeping k compares one character too far and can store an LCP that is longer than the truth.<\/td>\n<\/tr>\n<tr>\n<td>Reset k to 0 at every position<\/td>\n<td>The array comes out correct and the comparisons are quadratic on a string of identical characters. The decrement is the linear bound.<\/td>\n<\/tr>\n<tr>\n<td>Compare SA[i] with SA[i+1] while iterating in text order without the inverse<\/td>\n<td>Adjacent positions in the text are not adjacent in the suffix array. The neighbor has to be looked up through rank.<\/td>\n<\/tr>\n<tr>\n<td>Take the maximum LCP over all pairs by scanning a Cartesian product<\/td>\n<td>The maximum adjacent LCP is already the global maximum common prefix of any two distinct suffixes.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">The suffix array itself is prefix doubling or a linear construction. A constant-time longest common extension of two arbitrary suffixes is a range-minimum query on this LCP array. Kasai&#8217;s pass is the linear bridge between them.<\/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 builds the LCP array from a suffix array. The LCP of the suffix at rank r is at least the previous LCP minus one, so each text index is charged a constant amount of work. It prints the first three LCP entries <code>0 1 3<\/code>.<\/p>\n\n<pre><code class=\"language-python\">text = &quot;banana&quot;\nsa = sorted(range(len(text)), key=lambda i: text[i:])\nrank = [0] * len(text)\nfor r, i in enumerate(sa):\n    rank[i] = r\nlcp = [0] * len(text)\nk = 0\nfor i in range(len(text)):\n    if rank[i] == 0:\n        k = 0\n        continue\n    j = sa[rank[i] - 1]\n    while i + k &lt; len(text) and j + k &lt; len(text) and text[i + k] == text[j + k]:\n        k += 1\n    lcp[rank[i]] = k\n    if k:\n        k -= 1\nnaive = [0] * len(text)\nfor r in range(1, len(text)):\n    a, b = sa[r], sa[r - 1]\n    while a &lt; len(text) and b &lt; len(text) and text[a] == text[b]:\n        naive[r] += 1\n        a += 1\n        b += 1\nassert lcp == naive\nprint(*lcp[:3])\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\">Kasai&#8217;s algorithm builds the LCP array from a finished suffix array, which is the neighbor-height table in genome indexes and in string search. The suffix array alone does not give those heights. An FM-index then uses the Burrows-Wheeler transform of the same string.<\/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 hand-written LCP loop that resets to zero when the suffix array is large and repetitive. The inherited length is the whole point. Keep Kasai&#8217;s algorithm whenever an LCP array is required next to a suffix array.<\/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 Kasai&#8217;s algorithm returns the inequality that lets the matched length drop by only one as the text position advances. <strong>Kasai&#8217;s algorithm builds the LCP array in linear time by walking suffixes in text order and reusing the previous matched length minus one.<\/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: Kasai&#8217;s algorithm builds the LCP array of a string from its suffix array in O(n) time. LCP[i] is the length of the longest common prefix of the suffixes that are adjacent in sorted order, SA[i\u22121] and SA[i]. The algorithm walks the suffixes in text order and uses&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-207","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\/207","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=207"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/207\/revisions"}],"predecessor-version":[{"id":606,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/207\/revisions\/606"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=207"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=207"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=207"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}