Palindrome algorithms
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A palindrome reads identically forwards and backwards. We start with brute-force all-substring checking to see why naive verification takes cubic time, optimize to quadratic time by expanding around centres, and examine Manacher's linear algorithm.
Brute Force Substring Checking and Why It Is Slow
The brute force approach to palindromes enumerates every possible substring and checks each one, whether you need the longest palindromic substring or a count of all palindromes. An N-character string has N * (N + 1) / 2 substrings.
static boolean isPalindrome(String s, int i, int j) { // O(N) for one substring while (i < j) { if (s.charAt(i++) != s.charAt(j--)) return false; } return true;}
static int longestBrute(String s) { // O(N^2) substrings x O(N) check = O(N^3) int best = 0; for (int i = 0; i < s.length(); i++) for (int j = i; j < s.length(); j++) if (j - i + 1 > best && isPalindrome(s, i, j)) best = j - i + 1; return best;}For each substring S[i..j], naive checking runs two pointers from outer ends inward to verify character equality. Checking one substring takes O(N) time in the worst case.
Multiplying O(N^2) substrings by O(N) verification yields O(N^3) cubic time. For a string of length 2,000, 2,000^3 is 8 billion operations, causing immediate time limit exceeded errors.
Expand Around Centre in Quadratic O(N^2) Time
Notice that every palindrome is symmetric around a central axis. Instead of testing arbitrary boundaries, we can expand outwards from each possible centre.
Example 1 · Longest palindrome by checking every substring, brute force: O(N³) time, O(1) space
public class PalindromeCubicDemo { static boolean isPalindrome(String s, int i, int j) { while (i < j) { if (s.charAt(i++) != s.charAt(j--)) return false; } return true; }
static String longestPalindrome(String s) { String best = ""; for (int i = 0; i < s.length(); i++) { for (int j = i; j < s.length(); j++) { // every substring, then a full check if (j - i + 1 > best.length() && isPalindrome(s, i, j)) { best = s.substring(i, j + 1); } } } return best; }
public static void main(String[] args) { System.out.println("Longest in 'babad': " + longestPalindrome("babad")); System.out.println("Longest in 'cbbd': " + longestPalindrome("cbbd")); }}Longest in 'babad': bab Longest in 'cbbd': bb
What this code does
- Two loops pick every start and end: about N² / 2 substrings.
- isPalindrome() then compares letters from both ends, up to N / 2 steps.
- It prints bab and bb, the same as the expand version, in O(N³) time.
Example 2 · Longest palindrome by expanding around centres, better: O(N²) time, O(1) space
public class ExpandAroundCentreDemo { public static String longestPalindrome(String s) { if (s == null || s.length() < 1) return ""; int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) { int len1 = expand(s, i, i); // odd length int len2 = expand(s, i, i + 1); // even length int len = Math.max(len1, len2);
if (len > end - start + 1) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); }
private static int expand(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { left--; right++; } return right - left - 1; }
public static void main(String[] args) { System.out.println("Longest in 'babad': " + longestPalindrome("babad")); System.out.println("Longest in 'cbbd': " + longestPalindrome("cbbd")); }}Longest in 'babad': bab Longest in 'cbbd': bb
What this code does
- Expands outward from 2n - 1 centres (odd and even).
- Returns length (right - left - 1) once mismatch occurs.
- Runs in O(N^2) time and O(1) auxiliary space without DP table memory.
- Why faster: a palindrome grows from its centre and stops at the first mismatch, so inner letters are never checked again: O(N²) instead of O(N³).
Example 3 · Counting palindromic substrings by expanding: O(N²) time, O(1) space
public class CountPalindromesDemo { public static int countSubstrings(String s) { int count = 0; int n = s.length();
for (int i = 0; i < n; i++) { // Odd length palindromes count += expandCount(s, i, i); // Even length palindromes count += expandCount(s, i, i + 1); } return count; }
private static int expandCount(String s, int left, int right) { int matches = 0; while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { matches++; left--; right++; } return matches; }
public static void main(String[] args) { System.out.println("Count in 'abc': " + countSubstrings("abc")); System.out.println("Count in 'aaa': " + countSubstrings("aaa")); }}Count in 'abc': 3 Count in 'aaa': 6
What this code does
- In 'abc', only single-character substrings 'a', 'b', 'c' are palindromes (count = 3).
- In 'aaa', palindromes are 'a' (x3), 'aa' (x2), 'aaa' (x1), totaling 6.
- Executes in O(N^2) time and O(1) memory.
A string of length N has 2N - 1 potential centres: N odd-length centres at individual characters S[i] and N - 1 even-length centres between adjacent characters (S[i], S[i + 1]). Starting at each centre, we expand outward with left and right pointers while characters match. If a mismatch occurs, we stop immediately. Because each of the 2N centres expands at most N times, the entire algorithm runs in O(N^2) time and requires only O(1) auxiliary space.
Fix the error
Fix the compile error
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
This expands outwards from the middle letter of "racecar".
Error
CentreFix.java:5: error: cannot find symbol
while (left >= 0 && right < s.length && s.charAt(left) == s.charAt(right)) {
symbol: variable length
location: variable s of type StringThe Core Insight of Manacher's Linear Algorithm
Manacher's algorithm finds palindromes in strictly O(N) linear time. Just as the Z-algorithm reuses precomputed prefixes using a window, Manacher's algorithm reuses palindromic symmetry.
int mirror = 2 * c - i; // i reflected across the centre cif (i < r) p[i] = Math.min(r - i, p[mirror]); // reuse the mirror's radiuswhile (t.charAt(i + 1 + p[i]) == t.charAt(i - 1 - p[i])) p[i]++; // compare only past rif (i + p[i] > r) { c = i; r = i + p[i]; } // the window now reaches further rightManacher maintains a centre C and a right boundary R of the palindromic window discovered so far that reaches furthest right. When evaluating index i < R, its mirrored position across centre C is mirror = 2*C - i.
Because the substring around C is palindromic, the palindrome radius at i is at least as large as the radius at mirror: P[i] = min(R - i, P[mirror]). We only need to perform character comparisons when the palindrome extends beyond right boundary R.
Handling Even and Odd Lengths with Interleaving
A classic obstacle in palindrome algorithms is handling odd and even lengths separately. Manacher solves this elegantly by interleaving a special delimiter (like '#') between every character and at both ends: 'aba' becomes '#a#b#a#'.
Example 4 · Manacher's algorithm, optimal: O(N) time, O(N) space
public class ManacherDemo { public static String longestPalindrome(String s) { if (s == null || s.length() <= 1) return s;
// Transform: "aba" -> "^#a#b#a#$" StringBuilder sb = new StringBuilder("^"); for (char c : s.toCharArray()) sb.append('#').append(c); sb.append("#$"); String t = sb.toString();
int n = t.length(); int[] p = new int[n]; int c = 0, r = 0;
for (int i = 1; i < n - 1; i++) { int mirror = 2 * c - i; if (r > i) { p[i] = Math.min(r - i, p[mirror]); } while (t.charAt(i + 1 + p[i]) == t.charAt(i - 1 - p[i])) { p[i]++; } if (i + p[i] > r) { c = i; r = i + p[i]; } }
int maxLen = 0, centerIndex = 0; for (int i = 1; i < n - 1; i++) { if (p[i] > maxLen) { maxLen = p[i]; centerIndex = i; } } int start = (centerIndex - 1 - maxLen) / 2; return s.substring(start, start + maxLen); }
public static void main(String[] args) { System.out.println("Manacher longest in 'abacaba': " + longestPalindrome("abacaba")); System.out.println("Manacher longest in 'racecar': " + longestPalindrome("racecar")); }}Manacher longest in 'abacaba': abacaba Manacher longest in 'racecar': racecar
What this code does
- Interleaves '#' delimiters to unify odd and even palindromes.
- Reuses mirrored palindrome radii p[mirror] across center c.
- Runs in strictly O(N) time and O(N) space.
- Why faster: a palindrome inside a known bigger palindrome mirrors its twin, so the mirrored radius is reused and each letter is compared only a few times.
In the transformed string of length 2N + 1, every palindrome has an odd length with a single character centre, unifying odd and even cases into a single mathematical formula. The radius P[i] in the transformed string corresponds exactly to the length of the palindrome in the original string, enabling longest palindrome retrieval and total palindrome counts in O(N) time.
Next step
Check your understanding
10 quick questions