Data Structures · Visualization
Suffix Array: LCP Array
Suffix Array
The LCP (Longest Common Prefix) array stores, for each pair of neighboring suffixes in the sorted suffix array, how many leading characters they share. Time: O(n) with Kasai's algorithm (after the suffix array is built), O(n^2) naive. Space: O(n).
Big-O: Build O(n log n); pattern search O(m log n).
Suffix Array: LCP Array
Suffix ArrayThe LCP (Longest Common Prefix) array stores, for each pair of neighboring suffixes in the sorted suffix array, how many leading characters they share. Since alphabetically similar suffixes sit next to each other, this reveals repeated patterns in the original string very efficiently, and is a key ingredient for many advanced string algorithms.
How LCP Array Works
- Start with the suffix array already built and sorted.
- For each pair of adjacent suffixes in the sorted order, compare them character by character from the start.
- Count how many characters match before the first difference (or until one suffix ends).
- Store that count as the LCP value for that adjacent pair.
LCP Array Worked Example
Input: Suffix array [5,3,1,0,4,2] for 'banana' -> suffixes a, ana, anana, banana, na, nana
- LCP('a', 'ana') = 1 (share 'a')
- LCP('ana', 'anana') = 3 (share 'ana')
- LCP('anana', 'banana') = 0 (share nothing)
- LCP('banana', 'na') = 0
- LCP('na', 'nana') = 2 (share 'na')
Output: [1, 3, 0, 0, 2]
Press ▶ Run to watch it step by step.
def kasai(s, sa):
n = len(s)
rank = [0] * n # inverse permutation of sa
for i in range(n): rank[sa[i]] = i
lcp = [0] * (n - 1)
h = 0
for i in range(n): # O(n)
r = rank[i]
if r == n - 1: h = 0; continue
j = sa[r + 1]
while i + h < n and j + h < n and s[i + h] == s[j + h]:
h += 1
lcp[r] = h
if h > 0: h -= 1
return lcp # lcp[r] = LCP(sa[r], sa[r+1])
# example: lcp arrayBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
LCP Array Time & Space Complexity
When to Use LCP Array
- Finding the longest repeated substring in a text
- Efficient string comparison and pattern-matching algorithms
- Data compression techniques that rely on repeated substrings
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.