
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char* longestPalindrome(char* s) {
int n = strlen(s);
static char res[1000];
bool dp[n][n];
memset(dp, false, sizeof(dp));
int start = 0, maxLen = 1;
for (int i = 0; i < n; i++) dp[i][i] = true;
for (int i = 0; i < n - 1; i++) {
if (s[i] == s[i+1]) {
dp[i][i+1] = true;
start = i;
maxLen = 2;
}
}
for (int len = 3; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
if (s[i] == s[j] && dp[i+1][j-1]) {
dp[i][j] = true;
if (len > maxLen) {
start = i;
maxLen = len;
}
}
}
}
strncpy(res, s + start, maxLen);
res[maxLen] = '\0';
return res;
}
int main() {
char input[] = "babad";
printf("Longest Palindromic Substring: %s\n", longestPalindrome(input));
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | If the string is already a palindrome, each center will expand quickly and minimal comparisons are made. |
| Average Case | O(n^2) | Each character is treated as a center and expanded outward, leading to quadratic time in general. |
| Worst Case | O(n^2) | In the worst case, each expansion checks almost the entire string (e.g., for input like 'aaaaaaa'). |