ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING

Build the KMP Prefix Table

Learn how to build the kmp prefix table using a clear C program.

AdvancedPattern matchingString preprocessing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 0 1 2 0 1 2 3 4

COMPLETE C PROGRAM

Complete C implementation

ads-kmp-prefix-function.c
Open in compiler
#include <stdio.h>
#include <string.h>

int main(void)
{
    const char pattern[] = "ABABCABAB";
    int length = (int) strlen(pattern), prefix[20] = {0};
    for (int index = 1, border = 0; index < length;) {
        if (pattern[index] == pattern[border]) prefix[index++] = ++border;
        else if (border) border = prefix[border - 1];
        else prefix[index++] = 0;
    }
    for (int index = 0; index < length; index++) printf("%d%c", prefix[index], index == length - 1 ? '\n' : ' ');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0 0 1 2 0 1 2 3 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Reuse the longest proper prefix that is also a suffix after each mismatch.
  3. Display the computed result.

Reuse the longest proper prefix that is also a suffix after each mismatch.

EFFICIENCY

Time and space complexity

Time complexity

O(m)

Auxiliary space

O(pattern length)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.