Advanced
Longest Common Prefix (LCP)
Computing common prefixes between sorted suffixes.
Time Complexity
O(N)
Space Complexity
O(N)
Interactive Visualization
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
- 1Sorting suffixes to get the Suffix Array.
- 2Comparing adjacent suffixes in the sorted list.
- 3Calculating the length of their shared prefix.
- 4Storing 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).