String Matching Computing the longest prefix suffix array in kmp algorithm
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction to String Matching and the KMP Algorithm
String matching is an important problem in computer science, where the goal is to find occurrences of a string pattern within another string. One of the most efficient algorithms devised for string matching is the Knuth-Morris-Pratt (KMP) Algorithm, which preprocesses the pattern to achieve linear time complexity. A key component in KMP is the longest prefix suffix (LPS) array.
Understanding the LPS Array
The LPS array (also known as the prefix function or pi-table) for a given pattern is used to determine how far the pattern itself can be shifted while matching the text. Specifically, it indicates the longest proper prefix of the pattern that is also a suffix until the current position. This allows the algorithm to avoid redundant comparisons.
Constructing the LPS Array
Here's a step-by-step method to construct the LPS array:
- Initialize the LPS array with zeros.
- Start with an index
i = 1(aslps[0]is always0), and a length of the previous longest prefix suffix (len = 0). - Compare the character at position
iwith the character at positionlenin the pattern. • If they match, incrementlenand setlps[i] = len, then incrementi. • If they do not match andlen ≠ 0, setlen = lps[len - 1]. • If they do not match andlen = 0, setlps[i] = 0and incrementi. - Repeat step 3 until you have processed the entire pattern.
Let's illustrate this with an example.
Example: Constructing LPS Array
Consider the pattern "ABABCABAB". Here's how the LPS array is constructed:
• Initialize lps[] = \{0, 0, 0, 0, 0, 0, 0, 0, 0\}
.
• Index i = 1
, len = 0
.
• Pattern at i = 1
: No match, so lps[1] = 0
and move to i = 2
.
• Pattern at i = 2
: B
matches B
, len = 1
, so lps[2] = 1
and move to i = 3
.
• Pattern at i = 3
: A
matches A
, len = 2
, so lps[3] = 2
and move to i = 4
.
• Pattern at i = 4
: B
does not match A
, len = lps[len - 1] = 1
.
• Continue similarly until the end of the pattern.
The resulting LPS array is lps[] = \{0, 0, 1, 2, 0, 1, 2, 3, 4\}
.
How LPS Array is Used in KMP
Once the LPS array is prepared, the KMP algorithm uses it to skip characters in the pattern when a mismatch occurs in the text. Instead of resetting i
to the beginning of the pattern, the algorithm uses the LPS array to resume matching from a better point. This reduces the overall comparisons made, ensuring the algorithm works in time complexity, where is the length of the text and is the length of the pattern.
Analyzing Performance
The pre-processing step to compute the LPS array takes linear time . The actual pattern searching phase also takes linear time since each character in the text is processed at most once.
Key Points Summary
| Topic | Explanation |
| Problem | Efficiently find occurrences of a pattern in a text. |
| Key Data Structure | LPS (Longest Prefix Suffix) Array. |
| Purpose of LPS | Determines the optimal shift when a mismatch occurs. |
| Time Complexity | Preprocessing: ; Searching: |
| Example Pattern | "ABABCABAB" |
| Computed LPS | {0, 0, 1, 2, 0, 1, 2, 3, 4} |
Additional Details
- Boundary Cases: The LPS array can be generalized to handle special cases like repeating patterns or singular characters by ensuring the incremental logic within the loop accounts for each mismatch correctly.
- Real-World Application: KMP algorithm is used in text editors for searching words or phrases, in DNA sequence analysis, and in network data packet searching for identifying patterns or signatures.
Understanding the LPS array's role enhances the comprehension of the KMP algorithm's efficiency, making string matching a significantly more performant operation in computational tasks.
Related reading
- String pattern matching with one or zero mismatch
- String permutations rank data structure
- String similarity - Levenshtein distance
- String similarity how exactly does Bitap work?
- String search in string array in objective c
- String Tiling Algorithm
- String similarity score/hash
- String to unique integer hashing

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.