ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING

Apply Boyer–Moore Bad-Character Search

Learn how to apply boyer–moore bad-character search using a clear C program.

AdvancedPattern matchingString preprocessing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Index = 4

COMPLETE C PROGRAM

Complete C implementation

ads-boyer-moore-bad-character.c
Open in compiler
#include <stdio.h>
#include <string.h>

int main(void)
{
    const unsigned char text[] = "ABAAABCD", pattern[] = "ABC";
    int last[256], n = (int) strlen((const char *) text), m = (int) strlen((const char *) pattern);
    for (int i = 0; i < 256; i++) last[i] = -1;
    for (int i = 0; i < m; i++) last[pattern[i]] = i;
    int shift = 0;
    while (shift <= n - m) {
        int index = m - 1;
        while (index >= 0 && pattern[index] == text[shift + index]) index--;
        if (index < 0) { printf("Index = %d\n", shift); break; }
        int jump = index - last[text[shift + index]]; shift += jump > 1 ? jump : 1;
    }
    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

Index = 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Compare from the pattern end and jump past a mismatched character's last occurrence.
  3. Display the computed result.

Compare from the pattern end and jump past a mismatched character's last occurrence.

EFFICIENCY

Time and space complexity

Time complexity

Average sublinear

Auxiliary space

O(alphabet)

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.