ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Search with the Z Algorithm
Learn how to search with the z algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Matches: 0 2 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
const char combined[] = "ABA$ABABABA";
int length = (int) strlen(combined), z[30] = {0}, left = 0, right = 0;
for (int index = 1; index < length; index++) {
if (index <= right) z[index] = right - index + 1 < z[index - left] ? right - index + 1 : z[index - left];
while (index + z[index] < length && combined[z[index]] == combined[index + z[index]]) z[index]++;
if (index + z[index] - 1 > right) { left = index; right = index + z[index] - 1; }
}
printf("Matches:");
for (int index = 4; index < length; index++) if (z[index] == 3) printf(" %d", index - 4);
putchar('\n'); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Matches: 0 2 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Build Z values for pattern, separator and text; a full pattern-length value marks a match.
- Display the computed result.
Build Z values for pattern, separator and text; a full pattern-length value marks a match.
EFFICIENCY
Time and space complexity
Time complexity
O(n + 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.
