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.

AdvancedPattern matchingString preprocessing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Longest = geeksskeeg

COMPLETE C PROGRAM

Complete C implementation

ads-manacher-longest-palindrome.c
Open in compiler
#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;
}

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

Longest = geeksskeeg
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Reuse palindrome radii mirrored around the current rightmost palindrome.
  3. 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.