KMP algorithm
string matching
prefix suffix array
pattern searching
computer science algorithms

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.

Practice algorithms

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:

  1. Initialize the LPS array with zeros.
  2. Start with an index i = 1 (as lps[0] is always 0 ), and a length of the previous longest prefix suffix (len = 0 ).
  3. Compare the character at position i with the character at position len in the pattern. • If they match, increment len and set lps[i] = len , then increment i . • If they do not match and len ≠ 0 , set len = lps[len - 1] . • If they do not match and len = 0 , set lps[i] = 0 and increment i .
  4. 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 O(n+m)O(n + m) time complexity, where nn is the length of the text and mm is the length of the pattern.

Analyzing Performance

The pre-processing step to compute the LPS array takes linear time O(m)O(m). The actual pattern searching phase also takes linear time since each character in the text is processed at most once.

Key Points Summary

TopicExplanation
ProblemEfficiently find occurrences of a pattern in a text.
Key Data StructureLPS (Longest Prefix Suffix) Array.
Purpose of LPSDetermines the optimal shift when a mismatch occurs.
Time ComplexityPreprocessing: O(m)O(m); Searching: O(n+m)O(n + m)
Example Pattern"ABABCABAB"
Computed LPS{0, 0, 1, 2, 0, 1, 2, 3, 4}

Additional Details

  1. 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.
  2. 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.