Longest palindromic substring. Compare brute force, dynamic programming and expand around centre.
Problem
"babad" → "bab" (or "aba"); "cbbd" → "bb".
Pattern
Expand around centre: every palindrome mirrors around a centre, which is either a character (odd length) or a gap between two characters (even length): 2n − 1 centres.
Approach 1: Check every substring (feasible, O(n³))
class LongestPalBrute {
static String find(String s) {
String best = s.isEmpty() ? "" : s.substring(0, 1);
for (int i = 0; i < s.length(); i++)
for (int j = i + best.length(); j < s.length(); j++)
if (isPal(s, i, j)) best = s.substring(i, j + 1);
return best;
}
private static boolean isPal(String s, int i, int j) {
while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false;
return true;
}
}Approach 2: DP table (O(n²) time, O(n²) space)
pal[i][j] is true when s[i] == s[j] and the inside pal[i+1][j-1] is a palindrome.
class LongestPalDp {
static String find(String s) {
int n = s.length(), start = 0, len = n == 0 ? 0 : 1;
boolean[][] pal = new boolean[n][n];
for (int i = n - 1; i >= 0; i--)
for (int j = i; j < n; j++) {
pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || pal[i + 1][j - 1]);
if (pal[i][j] && j - i + 1 > len) { start = i; len = j - i + 1; }
}
return s.substring(start, start + len);
}
}Approach 3: Expand around centre (O(n²) time, O(1) space) — the expected answer
class LongestPalExpand {
static String find(String s) {
int start = 0, end = 0;
for (int c = 0; c < s.length(); c++) {
int len = Math.max(expand(s, c, c), expand(s, c, c + 1)); // odd and even centres
if (len > end - start) { start = c - (len - 1) / 2; end = c + len / 2 + 1; }
}
return s.substring(start, end);
}
private static int expand(String s, int l, int r) {
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
return r - l - 1;
}
}
class LongestPalDemo {
public static void main(String[] args) {
for (String s : new String[] {"babad", "cbbd", "forgeeksskeegfor", "a"}) {
System.out.println(LongestPalBrute.find(s) + " " + LongestPalDp.find(s) + " " + LongestPalExpand.find(s));
} // bab aba bab (both valid) / bb bb bb / geeksskeeg x3 / a a a
}
}Feasible → optimal
O(n³) brute force → O(n²) DP with O(n²) memory → O(n²) expand-around-centre with O(1) memory. Manacher's algorithm achieves O(n), but is rarely expected; mention it by name.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): count all palindromic substrings.
Use the same 2n − 1 centres and count every successful expansion step instead of tracking the longest. O(n²), O(1).
Related (same pattern): longest palindromic subsequence.
Not contiguous, so expansion does not apply; use DP: dp[i][j] = s[i] == s[j] ? dp[i+1][j-1] + 2 : max(dp[i+1][j], dp[i][j-1]), or LCS of the string with its reverse. O(n²).