LCP array
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The LCP array is a list that sits next to an alphabetically sorted list of word endings and records how many starting letters each neighbouring pair shares. It quietly answers questions about repeated text without any heavy comparing.
Practical use cases
- Web app: Finding the most repeated phrase in a blog or book. An editor tool for a CMS flags phrases a writer repeats too often. Comparing every part of the article against every other part is slow on a 100,000-word manuscript. With the LCP array, the largest number in the list points directly to the longest repeated phrase, so the warning appears right after saving.
- Web app: Duplicate content checker for an SEO dashboard. An SEO tool wants to tell site owners how much of a page is copied from another page of the same site. Sorting the text endings and reading the neighbour overlaps shows every long repeat in one pass, so a page report that took minutes is ready while the owner is still on the screen.
- Web app: Count of distinct words or fragments for analytics. A search-analytics page wants to show how many different fragments appear in a huge query log. Total possible fragments minus the overlaps in the LCP list gives that count directly, without storing every fragment in a set that would use up memory.
- System: Genome repeat finding. Biologists look for long sections of DNA that repeat, because repeats often mean something. After sorting the DNA endings, the neighbour-overlap numbers show those repeats immediately. Because the repeats sit right next to each other after sorting, no pair of far-apart endings ever needs to be compared with each other.
The story: The Neighbours Who Share a Start
In Raju's street, the houses were arranged in dictionary order of their owners' tail-end names: ana, anana, banana, na, nana, and so on. Every evening neighbours chatted over the fence, and Mira noticed something: names that start alike always live next to each other. If two far-apart houses share a long beginning, every house in between shares it too.
So Mira wrote one number on every fence: how many letters at the beginning the two neighbours have in common. "ana" and "anana" share three letters, so that fence says 3. "anana" and "banana" share none, so 0. This row of fence numbers is the LCP array, short for longest common prefix.
The fence numbers answer big questions almost for free. The biggest number tells the longest repeated piece of the word. Adding all the fence numbers and subtracting from the total count of prefixes tells how many different pieces the word contains. And the clever trick for building the array quickly (Kasai's algorithm) walks the suffixes in the original word order: if suffix i shared h letters with its neighbour, then suffix i+1 shares at least h-1, so the counter never needs to restart from zero.
How to spot this problem, and where you need it
You need to find repeated parts inside one large text, such as the longest repeated phrase or the number of different pieces, and checking every part against every other part takes forever.
Signs you need it
- You are asked for the longest repeated substring, or the number of distinct substrings, in a long string.
- Your code compares every starting position with every other starting position using two nested loops over the text.
- Reports that find duplicated passages run quickly on a paragraph but time out on a whole book or log file.
Where to use it in a project
- A writing or CMS tool that warns authors about repeated phrases or copy-pasted blocks in long content.
- A log analyser that looks for the longest repeating message pattern inside a very big log file.
- A DNA or text-mining tool that counts distinct fragments without storing every fragment in memory.
The solution
First sort all endings of the text alphabetically (a suffix array does this). Similar endings end up as neighbours. Now walk down the sorted list and write beside each pair how many starting letters they share; that list is the LCP array. The biggest number is the longest repeated piece, and taking the total number of possible pieces and subtracting the sum of the list counts the distinct ones. No extra comparing is needed.
Payoff: Before: comparing a 100,000-character text with itself, billions of checks. After: one sort and one pass, finishing in a fraction of a second.
Explain it like I am 8
Put names in alphabet order. Neighbours in the list start the same way more than far-away names do. Write next to each pair how many first letters they share. Those small numbers help you spot repeated pieces without checking everything again.
How it works, step by step
- First build the suffix array (sorted list of start positions) and an array
rankthat says where each start sits in it. - The LCP between sorted neighbours
sa[r-1]andsa[r]is how many first letters they share. - Do not compare every pair from scratch. Kasai's trick: go through the starts in text order i = 0, 1, 2...; keep
h, the match length; after each start reducehby one at most, never reset to zero. - For i, find its sorted neighbour above (
j = sa[rank[i] - 1]), growhwhile letters match, storelcp[rank[i]] = h, thenh--if it is above zero. - Use the array: max value = longest repeated substring; total suffix lengths minus sum of LCP = number of distinct substrings.
The code in four languages
PHP
<?php
// Kasai's algorithm: build the LCP array in O(n) from a suffix array.
function lcpArray(string $s, array $sa): array {
$n = strlen($s);
$rank = array_fill(0, $n, 0);
for ($i = 0; $i < $n; $i++) $rank[$sa[$i]] = $i;
$lcp = array_fill(0, $n, 0); // lcp[r] = common start of sa[r-1] and sa[r]
$h = 0;
for ($i = 0; $i < $n; $i++) {
if ($rank[$i] > 0) {
$j = $sa[$rank[$i] - 1]; // the neighbour just above in sorted order
while ($i + $h < $n && $j + $h < $n && $s[$i + $h] === $s[$j + $h]) $h++;
$lcp[$rank[$i]] = $h;
if ($h > 0) $h--; // next start shares at least h-1
} else {
$h = 0;
}
}
return $lcp;
}
$s = "banana";
$sa = range(0, strlen($s) - 1);
usort($sa, fn($a, $b) => strcmp(substr($s, $a), substr($s, $b))); // simple suffix array
$lcp = lcpArray($s, $sa);
echo implode(",", $sa), "\n"; // 5,3,1,0,4,2
echo implode(",", $lcp), "\n"; // 0,1,3,0,0,2
$best = max($lcp);
echo "longest repeat: ", substr($s, $sa[array_search($best, $lcp)], $best), "\n"; // ana
$total = 0; foreach ($sa as $st) $total += strlen($s) - $st;
echo "distinct substrings: ", $total - array_sum($lcp), "\n"; // 15JavaScript
// Kasai's algorithm: build the LCP array in O(n) from a suffix array.
function lcpArray(s, sa) {
const n = s.length;
const rank = new Array(n).fill(0);
for (let i = 0; i < n; i++) rank[sa[i]] = i;
const lcp = new Array(n).fill(0); // lcp[r] = common start of sa[r-1] and sa[r]
let h = 0;
for (let i = 0; i < n; i++) {
if (rank[i] > 0) {
const j = sa[rank[i] - 1]; // the neighbour just above in sorted order
while (i + h < n && j + h < n && s[i + h] === s[j + h]) h++;
lcp[rank[i]] = h;
if (h > 0) h--; // next start shares at least h-1
} else {
h = 0;
}
}
return lcp;
}
const s = "banana";
const sa = [...Array(s.length).keys()].sort((a, b) => (s.slice(a) < s.slice(b) ? -1 : 1)); // simple suffix array
const lcp = lcpArray(s, sa);
console.log(sa.join(",")); // 5,3,1,0,4,2
console.log(lcp.join(",")); // 0,1,3,0,0,2
const best = Math.max(...lcp);
console.log("longest repeat: " + s.substr(sa[lcp.indexOf(best)], best)); // ana
const total = sa.reduce((t, st) => t + s.length - st, 0);
console.log("distinct substrings: " + (total - lcp.reduce((a, b) => a + b, 0))); // 15Java
import java.util.*;
public class Main {
// Kasai's algorithm: build the LCP array in O(n) from a suffix array.
static int[] lcpArray(String s, Integer[] sa) {
int n = s.length();
int[] rank = new int[n];
for (int i = 0; i < n; i++) rank[sa[i]] = i;
int[] lcp = new int[n]; // lcp[r] = common start of sa[r-1] and sa[r]
int h = 0;
for (int i = 0; i < n; i++) {
if (rank[i] > 0) {
int j = sa[rank[i] - 1]; // the neighbour just above in sorted order
while (i + h < n && j + h < n && s.charAt(i + h) == s.charAt(j + h)) h++;
lcp[rank[i]] = h;
if (h > 0) h--; // next start shares at least h-1
} else {
h = 0;
}
}
return lcp;
}
public static void main(String[] args) {
String s = "banana";
Integer[] sa = new Integer[s.length()];
for (int i = 0; i < sa.length; i++) sa[i] = i;
Arrays.sort(sa, Comparator.comparing(s::substring)); // simple suffix array
int[] lcp = lcpArray(s, sa);
System.out.println(Arrays.toString(sa)); // [5, 3, 1, 0, 4, 2]
System.out.println(Arrays.toString(lcp)); // [0, 1, 3, 0, 0, 2]
int bestRow = 0;
for (int r = 1; r < lcp.length; r++) if (lcp[r] > lcp[bestRow]) bestRow = r;
int best = lcp[bestRow];
System.out.println("longest repeat: " + s.substring(sa[bestRow], sa[bestRow] + best)); // ana
int total = 0, lcpSum = 0;
for (int st : sa) total += s.length() - st;
for (int v : lcp) lcpSum += v;
System.out.println("distinct substrings: " + (total - lcpSum)); // 15
}
}Go
package main
import (
"fmt"
"sort"
)
// lcpArray is Kasai's algorithm: build the LCP array in O(n) from a suffix array.
func lcpArray(s string, sa []int) []int {
n := len(s)
rank := make([]int, n)
for i := 0; i < n; i++ {
rank[sa[i]] = i
}
lcp := make([]int, n) // lcp[r] = common start of sa[r-1] and sa[r]
h := 0
for i := 0; i < n; i++ {
if rank[i] > 0 {
j := sa[rank[i]-1] // the neighbour just above in sorted order
for i+h < n && j+h < n && s[i+h] == s[j+h] {
h++
}
lcp[rank[i]] = h
if h > 0 {
h-- // next start shares at least h-1
}
} else {
h = 0
}
}
return lcp
}
func main() {
s := "banana"
sa := make([]int, len(s))
for i := range sa {
sa[i] = i
}
sort.Slice(sa, func(a, b int) bool { return s[sa[a]:] < s[sa[b]:] }) // simple suffix array
lcp := lcpArray(s, sa)
fmt.Println(sa) // [5 3 1 0 4 2]
fmt.Println(lcp) // [0 1 3 0 0 2]
bestRow := 0
for r := 1; r < len(lcp); r++ {
if lcp[r] > lcp[bestRow] {
bestRow = r
}
}
best := lcp[bestRow]
fmt.Println("longest repeat:", s[sa[bestRow]:sa[bestRow]+best]) // ana
total, lcpSum := 0, 0
for _, st := range sa {
total += len(s) - st
}
for _, v := range lcp {
lcpSum += v
}
fmt.Println("distinct substrings:", total-lcpSum) // 15
}Time: O(n) after the suffix array exists · Extra space: O(n). Kasai never restarts the match counter from zero: it drops by at most one per step, so total work stays linear.
Watch out for
- Comparing neighbours in sorted order each from scratch. That can cost O(n²); use Kasai's trick instead.
- Mixing up rank and position:
sa[r]gives the start for rank r,rank[i]gives the rank for start i. - Forgetting that lcp[0] has no neighbour above (leave it 0).
Quick check
- What does lcp[r] store?
- Length of suffix r
- Common starting letters between sorted neighbours r-1 and r
- Number of repeats of the word
- What is the longest repeated substring in terms of the LCP array?
- The first value
- The maximum value (and the suffix there)
- The sum
- Why is Kasai's algorithm linear?
- It sorts quickly
- The match counter h drops by at most one per step instead of restarting
- It skips half the word