KMP prefix table
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
The Knuth-Morris-Pratt (KMP) algorithm is a classic pattern matching algorithm that finds occurrences of a word within a main text string efficiently. The efficiency of KMP largely stems from its pre-processing phase, which involves the creation of a prefix table (also known as the "lps" table, where "lps" stands for "longest proper prefix which is also a suffix"). This table is key to avoiding unnecessary re-evaluation of characters when a mismatch between the pattern and the text occurs.
Understanding the KMP Prefix Table
Definition
The prefix table helps in determining the next positions within the pattern to be evaluated after a mismatch. This avoids backtracking over the text, which forms the basis for the KMP algorithm's efficiency.
Construction of the Prefix Table
To construct the prefix table for a pattern P
of length m
, you follow these steps:
- Initialize:
- Let
lpsbe an array of lengthm, initialized to zero. - Set
length = 0, which will keep track of the length of the current longest prefix suffix. - Start iterating over the pattern from index
1(sincelps[0]is always0).
- **Iterate and Update
lps**:- For each index
ifrom 1 tom - 1:- If
P[i]matchesP[length], incrementlengthby 1 and setlps[i] = length. - If
P[i]does not matchP[length], andlengthis not zero, setlengthtolps[length - 1]. - If
lengthis zero, simply setlps[i] = 0.
Example
Let's construct the lps array for the pattern ABABCABAB
.
| Index | Pattern | Length | LPS Array State |
| 0 | A | 0 | [0] |
| 1 | AB | 0 | [0, 0] |
| 2 | ABA | 1 | [0, 0, 1] |
| 3 | ABAB | 2 | [0, 0, 1, 2] |
| 4 | ABABC | 0 | [0, 0, 1, 2, 0] |
| 5 | ABABCA | 1 | [0, 0, 1, 2, 0, 1] |
| 6 | ABABCAB | 2 | [0, 0, 1, 2, 0, 1, 2] |
| 7 | ABABCABA | 3 | [0, 0, 1, 2, 0, 1, 2, 3] |
| 8 | ABABCABAB | 4 | [0, 0, 1, 2, 0, 1, 2, 3, 4] |
Notice how the lps
array provides crucial information for each prefix of the pattern.
Utilizing the lps
Table
During the search phase of the KMP algorithm, the prefix table helps to determine if and how the pattern can be shifted within the text without unnecessary shifts. When a mismatch is found after j
characters matched, we use the lps
table to skip comparisons rather than resetting j
to zero.
Algorithm Efficiency
Time Complexity
- Pre-processing Phase: The prefix table creation runs in linear time, , where
mis the length of the pattern. - Search Phase: Given the prefix table, the search phase also operates in linear time, , where
nis the length of the text.
Overall, the KMP algorithm runs in time, making it highly efficient for pattern matching.
Space Complexity
The KMP algorithm requires space to store the prefix table, which is relatively low compared to other algorithms that may require additional space for backtracking.
Additional Details
Comparison with Other Algorithms
- Naive Pattern Matching: This approach has a time complexity of due to repeated checks and backtracking.
- Boyer-Moore Algorithm: This algorithm leverages mismatch heuristics, which can lead to sub-linear time complexity in many scenarios, making it faster than KMP in practice but more complex to implement.
Applications
- Text editors for implementing "find" functionality.
- DNA sequence analysis, where searching for genetic patterns is common.
- Network intrusion detection systems to locate patterns of malicious activities.
Summary Table
| Topic | Details |
| Algorithm Name | Knuth-Morris-Pratt (KMP) |
| Key Component | Prefix Table (lps table) |
| Prefix Table Use | Avoid unnecessary character checks after mismatches |
| Complexity - Time | |
| Complexity - Space | |
| Strengths | Linear time complexity, no backtracking |
| Comparison | Outperforms Naive, simpler than Boyer-Moore in terms of implementation |
| Applications | Text search, bioinformatics, network security |
The KMP algorithm and its prefix table continue to be valuable in both theoretical computer science and practical applications, providing a foundation for efficient pattern matching techniques.
Related reading
- Knapsack algorithm with an additional property
- Knapsack Equation with item groups
- Knapsack how to add item type to existing solution
- Knapsack with continuous non distinct constraint
- knapsack with weight only
- KNN in Tensorflow - Using Graph to predict unseen data
- kNN state-of-the-art implementation
- Known algorithm for efficiently distributing items and satisfying minima?

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.