ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Find the Longest Palindrome with Manacher's Algorithm
Learn how to find the longest palindrome with manacher's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Longest = geeksskeeg
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
const char text[] = "forgeeksskeegfor";
char transformed[80] = "^"; int length = 1;
for (int i = 0; text[i]; i++) { transformed[length++] = '#'; transformed[length++] = text[i]; }
transformed[length++] = '#'; transformed[length++] = '$'; transformed[length] = '\0';
int radius[80] = {0}, center = 0, right = 0, best = 0, best_center = 0;
for (int i = 1; i < length - 1; i++) {
int mirror = 2 * center - i;
if (i < right) radius[i] = radius[mirror] < right - i ? radius[mirror] : right - i;
while (transformed[i + 1 + radius[i]] == transformed[i - 1 - radius[i]]) radius[i]++;
if (i + radius[i] > right) { center = i; right = i + radius[i]; }
if (radius[i] > best) { best = radius[i]; best_center = i; }
}
int start = (best_center - best) / 2;
printf("Longest = %.*s\n", best, text + start);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Longest = geeksskeeg
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Reuse palindrome radii mirrored around the current rightmost palindrome.
- Display the computed result.
Reuse palindrome radii mirrored around the current rightmost palindrome.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
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.
