Reading history

KMP Algorithm in C: Fast String Pattern Matching

6 min read 0 views

Learn the Knuth-Morris-Pratt (KMP) string matching algorithm in C: the LPS table, linear-time search, overlapping matches and comparison with naive search.

Finding a word inside a long text is one of the most common jobs a program does, from the Find box in an editor to searching DNA sequences. The obvious method slides the pattern along one position at a time and compares from scratch, which can be painfully slow on repetitive text. The Knuth–Morris–Pratt (KMP) algorithm notices how much of the pattern has already matched and never moves backwards in the text, guaranteeing O(n + m) time.

In this lesson you will learn

  • Why naive pattern search can take O(n × m)
  • The LPS (longest proper prefix that is also a suffix) table
  • Building the LPS table in O(m)
  • Searching with KMP in O(n)
  • Finding overlapping matches

You should be comfortable with strings in C.

The LPS Table

#include <stdio.h>
#include <string.h>

/* Build the LPS table: lps[i] = length of the longest proper prefix of
   pattern[0..i] that is also a suffix of it */
void build_lps(const char *pat, int m, int *lps) {
    int len = 0;
    lps[0] = 0;
    for (int i = 1; i < m; ) {
        if (pat[i] == pat[len]) lps[i++] = ++len;
        else if (len > 0) len = lps[len - 1];          /* fall back, do not move i */
        else lps[i++] = 0;
    }
}

int main(void) {
    const char *pats[] = {"ABABCABAB", "AAAA", "ABCDE", "AABAACAABAA"};
    for (int p = 0; p < 4; p++) {
        int m = (int)strlen(pats[p]), lps[32];
        build_lps(pats[p], m, lps);
        printf("%-12s LPS: ", pats[p]);
        for (int i = 0; i < m; i++) printf("%d ", lps[i]);
        printf("\n");
    }
    return 0;
}

Output

ABABCABAB    LPS: 0 0 1 2 0 1 2 3 4 
AAAA         LPS: 0 1 2 3 
ABCDE        LPS: 0 0 0 0 0 
AABAACAABAA  LPS: 0 1 0 1 2 0 1 2 3 4 5
  • For each position i in the pattern, lps[i] is the length of the longest proper prefix (not the whole string) of pattern[0..i] that is also a suffix of it.
  • For “ABABCABAB”, the last value is 4: “ABAB” appears both at the start and at the end.
  • “AAAA” gives 0 1 2 3 because every prefix of A’s is also a suffix. “ABCDE” has no repeated beginnings, so all values are 0.
  • When a character does not match, len = lps[len - 1] falls back to the next shorter candidate without moving i, so the whole table is built in O(m).
#include <stdio.h>
#include <string.h>

static void build_lps(const char *pat, int m, int *lps) {
    int len = 0;
    lps[0] = 0;
    for (int i = 1; i < m; ) {
        if (pat[i] == pat[len]) lps[i++] = ++len;
        else if (len > 0) len = lps[len - 1];
        else lps[i++] = 0;
    }
}

/* KMP search: the text index i never moves backwards */
int kmp_search(const char *text, const char *pat) {
    int n = (int)strlen(text), m = (int)strlen(pat), lps[64];
    int found = 0, comparisons = 0;
    build_lps(pat, m, lps);
    for (int i = 0, j = 0; i < n; ) {
        comparisons++;
        if (text[i] == pat[j]) {
            i++; j++;
            if (j == m) {
                printf("  match at index %d\n", i - m);
                found++;
                j = lps[j - 1];                      /* keep going for overlapping matches */
            }
        } else if (j > 0) {
            j = lps[j - 1];                          /* reuse what already matched */
        } else {
            i++;
        }
    }
    printf("  %d match(es), %d character comparisons for text length %d\n", found, comparisons, n);
    return found;
}

/* Naive search for comparison: restart one position later after each mismatch */
static int naive_comparisons(const char *text, const char *pat) {
    int n = (int)strlen(text), m = (int)strlen(pat), c = 0;
    for (int s = 0; s + m <= n; s++)
        for (int j = 0; j < m; j++) { c++; if (text[s + j] != pat[j]) break; }
    return c;
}

int main(void) {
    const char *text = "ABABDABACDABABCABABABABCABAB";
    const char *pat = "ABABCABAB";
    printf("Searching \"%s\" in \"%s\"\n", pat, text);
    kmp_search(text, pat);

    char worst[64];
    memset(worst, 'A', 40); worst[40] = '\0';
    printf("Worst case for naive search: 40 A's, pattern AAAAAAAB\n");
    kmp_search(worst, "AAAAAAAB");
    printf("  naive search needs %d comparisons\n", naive_comparisons(worst, "AAAAAAAB"));
    return 0;
}

Output

Searching "ABABCABAB" in "ABABDABACDABABCABABABABCABAB"
  match at index 10
  match at index 19
  2 match(es), 34 character comparisons for text length 28
Worst case for naive search: 40 A's, pattern AAAAAAAB
  0 match(es), 73 character comparisons for text length 40
  naive search needs 264 comparisons
  • i moves through the text and j through the pattern. On a match both advance; when j reaches the pattern length, a match is reported at i - m.
  • On a mismatch after j characters had matched, those characters are known. The pattern can shift so that its prefix of length lps[j - 1] lines up with the text already read, and comparison continues from there. The text index i never goes back.
  • After a full match, j = lps[j - 1] lets the search find overlapping matches.
  • On the repetitive text of 40 A’s, KMP makes 73 comparisons while the naive method makes 264. The gap grows with longer text and patterns: KMP is O(n + m), naive is O(n × m) in the worst case.

String Matching Algorithms

AlgorithmWorst caseIdea
NaiveO(n × m)Try every starting position
KMPO(n + m)Reuse matched prefix information (LPS)
Rabin–KarpO(n × m), O(n + m) expectedCompare rolling hash values first
Boyer–MooreO(n × m), often sublinear in practiceCompare from the end of the pattern and skip ahead

The C library function strstr finds the first match; real library implementations use fast algorithms internally, but KMP is the classic one to learn and to write in interviews.

Common Mistakes

  1. Setting lps[0] to anything other than 0; a single character has no proper prefix.
  2. Moving i forward on a fallback while building the table or searching, which skips characters.
  3. Resetting j to 0 after a full match, which misses overlapping matches.
  4. Calling strlen inside the loop condition, turning an O(n) loop into O(n2).

Practice Exercises

Exercise 1. Compute the LPS table for “ABACABAB”.

Show answer

0 0 1 0 1 2 3 2. At the last position, “ABA” + “B” does not extend the prefix “ABAC”, so it falls back to “AB”, length 2.

Exercise 2. Use the LPS table to check whether a string is made of a repeated substring, such as “abcabcabc”.

Show answer
int repeated(const char *s) {
    int n = (int)strlen(s), lps[256];
    build_lps(s, n, lps);
    int p = n - lps[n - 1];            /* length of the smallest period */
    return lps[n - 1] > 0 && n % p == 0;
}

For “abcabcabc”, lps[8] is 6, so the period is 3 and 9 is divisible by 3.

Frequently Asked Questions

Is the LPS table the same as the failure function?

Yes. Different books call it the prefix function, failure function or LPS array. Some define it shifted by one position, so check the convention when comparing code.

Where is KMP used besides text search?

In DNA and protein sequence analysis, network intrusion detection that scans packets for known signatures, and problems about periods and borders of strings.

Summary

  • The LPS table records how much of the pattern can be reused after a mismatch.
  • Building it takes O(m); searching takes O(n).
  • The text index never moves backwards, so KMP is O(n + m) in every case.
  • Setting j = lps[j - 1] after a match finds overlapping occurrences.

Next: Bellman-Ford Algorithm in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *