Skip to content
Advanced

Longest Common Prefix (LCP)

Computing common prefixes between sorted suffixes.

Time Complexity
O(N)
Space Complexity
O(N)

Interactive Visualization

Finding Longest Common Prefix
A
ANA
LCP1
ANA
ANANA
LCP3

Technical Guide

The Longest Common Prefix (LCP) Array is an auxiliary data structure for Suffix Arrays. It stores the length of the longest common prefix between each pair of consecutive suffixes in the sorted suffix array. This allows us to speed up string matching and perform complex analysis like finding the number of distinct substrings in O(N).

Logical Phases

  • 1
    Sorting suffixes to get the Suffix Array.
  • 2
    Comparing adjacent suffixes in the sorted list.
  • 3
    Calculating the length of their shared prefix.
  • 4
    Storing these values in a linear array.

Implementation

lcp[i] = commonPrefix(suffixes[i], suffixes[i-1]);

Expert Pitfalls

Calculating each LCP from scratch takes O(N^2); use Kasai's algorithm for O(N).