Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding the Knuth-Morris-Pratt (KMP) String Matching Algorithm

Tech Nov 18 10

Introduction to KMP

The Knuth-Morris-Pratt (KMP) algorithm is a classic string-matching algorithm designed to efficiently find occurrences of a "pattern" string within a larger "text" string. Unlike simpler approaches, KMP avoids re-examining characters that have already been matched, leading to a significant performance improvemant, especially for large texts and patterns.

Consider a scenario where you need to locate a specific word within a document, or identify a specific DNA sequence within a genome. These are practical applications where KMP's efficiency shines. The algorithm operates by preprocessing the pattern to create a "prefix table" (often denoted as nxt or lps for "longest proper prefix which is also a suffix"), which is then used during the search phase to skip unnecessary comparisons.

The Brute-Force Approach

A straightforward, albeit inefficient, method for string matching is the Brute-Force algorithm. This approach involves sliding the patttern over the text one position at a time and, for each position, comparing the pattern character by character with the corresponding substring of the text.

If a mismatch is found at any point, the pattern is shifted by one position, and the comparison starts over from the beginning of the pattern. This method has a worst-case time complexity of O(n*m), where n is the length of the text and m is the length of the pattern. This is because, in the worst case, every character of the text is compared with every character of the pattern for each potential starting position.

Here's a basic implementation of the Brute-Force approach:

// C++ example of Brute-Force string matching
#include <iostream>
#include <string>

void bruteForceSearch(const std::string& text, const std::string& pattern) {
    int n = text.length();
    int m = pattern.length();

    for (int i = 0; i <= n - m; ++i) {
        bool match = true;
        for (int j = 0; j < m; ++j) {
            if (text[i + j] != pattern[j]) {
                match = false;
                break;
            }
        }
        if (match) {
            std::cout << "Pattern found at index: " << i << std::endl;
        }
    }
}

Optimizing with KMP

The key insight of the KMP algorithm is to avoid re-examining characters in the text that are already known to match. When a mismatch occurs, KMP uses the information from the pattern's prefix table to determine the next position in the pattern to compare, effectively "jumping" over parts of the pattern that are already known to match a prefix of the text.

For example, if the pattern "ABCDAB" is being matched against the text "ABCABCDAB", and a mismatch occurs after matching "ABCAB", the algorithm doesn't restart the comparison from the beginning of the pattern. Instead, it uses the prefix table to know that the suffix "AB" of the already matched part also serves as a prefix of the pattern. Thus, it can continue the comparison from the 'C' in the pattern, skipping the redundant "AB" comparison.

The Prefix Table (nxt array)

The prefix table, often called nxt or lps (Longest Proper Prefix which is also a Suffix), is the core of the KMP algorithm. For each position i in the patttern, nxt\[i\] stores the length of the longest proper prefix of the pattern pattern\[0..i\] that is also a suffix of this substring.

This table allows the algorithm to "jump back" within the pattern when a mismatch occurs, rather than restarting from the beginning. If a mismatch happens at position j in the pattern, the algorithm can immediately shift the pattern so that the prefix ending at nxt\[j-1\] aligns with the suffix of the text that was just matched.

Implementation Details

The KMP algorithm consists of two main parts: constructing the prefix table and performing the actual search using this table.

1. Constructing the Prefix Table

The prefix table is constructed in a single pass through the pattern. We use a variable k to keep track of the length of the current longest prefix-suffix. For each character in the pattern (starting from the second character), we compare it with the character at position k. If they match, we increment k and set nxt\[i\] = k. If they don't match, we backtrack using the previously computed values in the nxt table until we find a match or reach the beginning of the pattern.

// C++ function to compute the prefix table
void computePrefixTable(const std::string& pattern, int* prefix_table) {
    int m = pattern.length();
    int k = 0; // Length of the previous longest prefix suffix

    prefix_table[0] = 0; // By definition, the first character has no proper prefix-suffix

    for (int i = 1; i < m; ++i) {
        // If characters don't match, fall back to the previous longest prefix-suffix
        while (k > 0 && pattern[k] != pattern[i]) {
            k = prefix_table[k - 1];
        }

        // If characters match, increment the length of the current prefix-suffix
        if (pattern[k] == pattern[i]) {
            k++;
        }

        prefix_table[i] = k;
    }
}

2. The Search Algorithm

During the search phase, we maintain two indices: text\_index for the text and pattern\_index for the pattern. We iterate through the text, comparing characters. If they match, we advance both indices. If they don't match, and pattern\_index is not at the start of the pattern, we use the prefix table to update pattern\_index to the length of the longest prefix that is also a suffix of the already matched part. If pattern\_index is at the start, we simply advance text\_index.

When pattern\_index reaches the length of the pattern, it means we have found a match. We then print the starting position (calculated as text\_index - pattern\_index) and reset pattern\_index using the prefix table to continue searching for subsequent occurrences.

// C++ function to perform KMP search
void kmpSearch(const std::string& text, const std::string& pattern) {
    int n = text.length();
    int m = pattern.length();

    if (m == 0) return; // Empty pattern

    int* prefix_table = new int[m];
    computePrefixTable(pattern, prefix_table);

    int text_index = 0;
    int pattern_index = 0;

    while (text_index < n) {
        if (text[text_index] == pattern[pattern_index]) {
            text_index++;
            pattern_index++;
        }

        if (pattern_index == m) {
            // Match found
            std::cout << "Pattern found at index: " << (text_index - pattern_index) << std::endl;
            pattern_index = prefix_table[pattern_index - 1]; // Continue searching
        } else if (text_index < n && text[text_index] != pattern[pattern_index]) {
            if (pattern_index != 0) {
                pattern_index = prefix_table[pattern_index - 1];
            } else {
                text_index++;
            }
        }
    }

    delete[] prefix_table;
}

Complete KMP Example

Here is a complete, runnable C++ program demonstrating the KMP algorithm, including the prefix table construction and the search function.

// Complete KMP String Matching Algorithm in C++
#include <iostream>
#include <string>
#include <vector>

// Function to compute the prefix table (nxt array)
void computePrefixTable(const std::string& pattern, std::vector<int>& prefix_table) {
    int m = pattern.length();
    int k = 0; // Length of the previous longest prefix suffix

    prefix_table[0] = 0; // By definition, the first character has no proper prefix-suffix

    for (int i = 1; i < m; ++i) {
        // If characters don't match, fall back to the previous longest prefix-suffix
        while (k > 0 && pattern[k] != pattern[i]) {
            k = prefix_table[k - 1];
        }

        // If characters match, increment the length of the current prefix-suffix
        if (pattern[k] == pattern[i]) {
            k++;
        }

        prefix_table[i] = k;
    }
}

// Function to perform KMP search
void kmpSearch(const std::string& text, const std::string& pattern) {
    int n = text.length();
    int m = pattern.length();

    if (m == 0) return; // Empty pattern

    std::vector<int> prefix_table(m);
    computePrefixTable(pattern, prefix_table);

    int text_index = 0;
    int pattern_index = 0;

    while (text_index < n) {
        if (text[text_index] == pattern[pattern_index]) {
            text_index++;
            pattern_index++;
        }

        if (pattern_index == m) {
            // Match found
            std::cout << "Pattern found at index: " << (text_index - pattern_index) << std::endl;
            pattern_index = prefix_table[pattern_index - 1]; // Continue searching
        } else if (text_index < n && text[text_index] != pattern[pattern_index]) {
            if (pattern_index != 0) {
                pattern_index = prefix_table[pattern_index - 1];
            } else {
                text_index++;
            }
        }
    }
}

int main() {
    std::string text = "ABABDABACDABABCABAB";
    std::string pattern = "ABABCABAB";

    std::cout << "Text: " << text << std::endl;
    std::cout << "Pattern: " << pattern << std::endl;
    std::cout << "Search results:" << std::endl;

    kmpSearch(text, pattern);

    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.