ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Search with a Pattern Finite Automaton
Learn how to search with a pattern finite automaton using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Matches: 0 9 12
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
const char text[] = "AABAACAADAABAABA", pattern[] = "AABA";
int m = (int) strlen(pattern), transition[5][2] = {{1,0},{2,0},{2,3},{4,0},{2,0}}, state = 0;
printf("Matches:");
for (int index = 0; text[index]; index++) {
state = transition[state][text[index] == 'B'];
if (state == m) printf(" %d", index - m + 1);
}
putchar('\n'); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Matches: 0 9 12
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Treat the matched-prefix length as an automaton state and consume each text character once.
- Display the computed result.
Treat the matched-prefix length as an automaton state and consume each text character once.
EFFICIENCY
Time and space complexity
Time complexity
O(n) after preprocessing
Auxiliary space
O(m * 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.
