Learn the pattern · ~14 min
Palindromic Substrings
also called expand around center, is_pal table
A palindrome is a smaller palindrome with one matching letter added on each side, so grow every palindrome from its middle (or fill pal[i][j] from pal[i+1][j-1]) instead of re-checking each substring.
Reach for it when you read
- +"Longest" or "how many" palindromic substrings, or "is
s[i..j]a palindrome?" asked for many pairs. - +Split a string so every piece is a palindrome: list all splits, or find the fewest cuts.
- +Longest palindromic subsequence, or the fewest insertions/deletions that make a string a palindrome.
- +Your brute force checks every substring letter by letter: O(n³).
Not this one when
- ×Is this one whole string a palindrome? Two pointers from the ends, no table.
- ×Can the letters be rearranged into a palindrome? Count letters with odd counts; order doesn't matter.
- ×Palindromes in a string of a million letters: O(n²) is too slow, use Manacher's algorithm.
Learn Palindromic Substrings
First, what is a palindrome?
A palindrome reads the same from both ends. level is one, bcb is one, a single letter like c is one. ab is not: it starts with a and ends with b.
Strip the two end letters of a palindrome and a palindrome is left: level becomes eve. That gives a test:
s[i..j]is a palindrome exactly whens[i] == s[j]and the insides[i+1..j-1]is a palindrome.
One or two letters have no inside, so only their ends matter. The palindrome table pal[i][j] writes this answer down once for every piece, so "is this piece a palindrome?" becomes one lookup.
Filling the table
Take s = "aabcb" (indices 0 to 4). A piece only asks about the piece just inside it, which is two letters shorter. So go by length, shortest first, and the answer you need is always already written.
| piece | what happens | palindrome? |
|---|---|---|
| a, a, b, c, b | one letter reads the same both ways | yes, all 5 |
| aa | ends a = a, nothing inside | yes |
| ab, bc, cb | the ends differ, stop | no |
| aab, abc | the ends differ | no |
| bcb | ends b = b, so look up the inside c: yes |
yes |
| aabc, abcb, aabcb | the ends differ | no |
Only bcb ever looked inside; every other piece was settled by its ends. That's 7 palindromes: five letters, aa and bcb.
The code for it
vector<vector<bool>> pal(n, vector<bool>(n, false));
for (int i = n - 1; i >= 0; i--) // from the right, so row i + 1 is ready
for (int j = i; j < n; j++)
pal[i][j] = s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1]);You don't need to memorise this. It's the table above: the ends must match, and the inside must already be a palindrome.
Why does i go backwards, from n − 1 down to 0? Because pal[i][j] reads pal[i + 1][j − 1], which sits in row i + 1. Running i from the right means row i + 1 is finished before row i starts. Run i from 0 and you'd read a row that is still all false.
Fine, but how does this help us?
Here's a classic problem: Palindrome Partitioning II. Cut the string into pieces so that every piece is a palindrome, using as few cuts as possible.
For "aabcb", list every way that works:
| pieces | cuts | why it works |
|---|---|---|
a | a | b | c | b |
4 | every letter alone always works |
aa | b | c | b |
3 | "aa" is a palindrome |
a | a | bcb |
2 | "bcb" is a palindrome |
aa | bcb |
1 | both pieces are palindromes |
No split has 0 cuts, because aabcb itself is not a palindrome. So the answer is 1: aa | bcb.
The brute force
The choices: look at the end of the string. The last piece is some palindrome s[i..j] that ends there. Pick one, cut in front of it, and solve the prefix before it the same way. If the whole prefix is already a palindrome, it needs 0 cuts.
bool isPal(int i, int j) { // letter by letter
while (i < j) if (s[i++] != s[j--]) return false;
return true;
}
int cuts(int j) { // fewest cuts for s[0..j]
if (isPal(0, j)) return 0; // the whole prefix is one piece
int best = INT_MAX;
for (int i = 1; i <= j; i++) // last piece is s[i..j]
if (isPal(i, j)) best = min(best, cuts(i - 1) + 1);
return best;
}
// answer: cuts(n - 1)Draw the calls for "aabcb". Only two last pieces end at index 4, b and bcb:
- cuts("aabcb")
- last piece "b" → 1 + cuts("aabc")
- last piece "c" → 1 + cuts("aab")
- last piece "b" → 1 + cuts("aa") = 0
- last piece "bcb" → 1 + cuts("aa") = 0
The left branch gives 3 cuts, the right one 1. Correct, but look at a bad input: "baaa…a". No prefix but b is a palindrome, yet every run of as at the end is one, so each call branches into every shorter prefix. That's 2ⁿ⁻¹ calls: 524,288 for n = 20, and a 602-digit number for n = 2000. Already at n = 30 it takes over a second. Time limit exceeded.
The one thought: the same question comes back
Look at the tree again. cuts("aa") appears twice: once at the bottom of the left branch, once at the end of the right one.
Does the answer for "aa" care how you got there? No. Peel off b, c, b or the single piece bcb: what's left is the prefix s[0..1] either way, and it needs 0 cuts. The question depends on one number, where the prefix ends.
So there are only n different questions, cuts(0) to cuts(n − 1). The exponential tree is the same n questions asked over and over. Answer each one once and write it down.
Memoise it
int cutsMemo(int j) { // memo starts as all -1
if (memo[j] != -1) return memo[j]; // asked before: reuse it
if (isPal(0, j)) return memo[j] = 0;
int best = INT_MAX;
for (int i = 1; i <= j; i++)
if (isPal(i, j)) best = min(best, cutsMemo(i - 1) + 1);
return memo[j] = best;
}Now each j is solved once. But each tries up to n last pieces, and isPal checks each letter by letter: O(n³). On "baaa…a" with n = 2000 that's about 7 × 10⁸ letter checks. It still finishes in about 0.2 s, so at this problem's limit it would pass, but at n = 5000 it takes 3 s.
The palindrome table removes that inner scan. Build pal[i][j] first, and every check becomes one lookup.
The bottom-up table
cut[j] = fewest cuts for the prefix s[0..j]. It only reads cut[i − 1] with i − 1 < j, so fill j from left to right and everything it needs is ready.
vector<int> cut(n);
for (int j = 0; j < n; j++) {
if (pal[0][j]) { cut[j] = 0; continue; } // the prefix is one piece
cut[j] = j; // worst case: a cut after every letter
for (int i = 1; i <= j; i++)
if (pal[i][j]) cut[j] = min(cut[j], cut[i - 1] + 1); // last piece is s[i..j]
}
// answer: cut[n - 1]Dry run
Same string, "aabcb". For each j, the last pieces are the palindromes that end at j.
| j | prefix | palindromic last pieces | what happens | cut[j] |
|---|---|---|---|---|
| 0 | a | the whole prefix | pal[0][0], one piece |
0 |
| 1 | aa | the whole prefix | pal[0][1], one piece |
0 |
| 2 | aab | b | cut[1] + 1 = 1 | 1 |
| 3 | aabc | c | cut[2] + 1 = 2 | 2 |
| 4 | aabcb | b, bcb | b: cut[3] + 1 = 3; bcb: cut[1] + 1 = 1 |
1 |
cut[4] = 1, the same answer as the brute force.
Why it's O(n²)
Count cells, not loops. The table has about n²/2 cells, each filled once from one other cell. The cut loop tries about n²/2 pairs (i, j), one lookup each. So O(n²) time and space: about 2 × 10⁶ steps for n = 2000.
From 2ⁿ calls down to n², by asking each prefix once and each piece once.
Count them? Add up the yes cells
Palindromic Substrings asks how many pieces are palindromes. That's the number of true cells:
int count = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) count += pal[i][j];On "aabcb" that's 7. The longest palindromic substring is the true cell with the biggest j − i: bcb.
A subsequence? Store a length
A subsequence keeps letters in order but may skip some. Now a cell stores a number: dp[i][j] = the longest palindromic subsequence inside s[i..j]. Equal ends both join it; different ends mean one of them has to go.
if (s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1] + 2; // both ends join
else dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); // drop one endSame fill order, with dp[i][i] = 1 and cells where i > j left at 0. On "aabcb" the answer is 3 (bcb).
Fewest insertions? Store a cost
Minimum Insertion Steps: equal ends cost nothing, a mismatch pays one letter to copy an end across.
if (s[i] == s[j]) ins[i][j] = ins[i + 1][j - 1];
else ins[i][j] = 1 + min(ins[i + 1][j], ins[i][j - 1]);On "aabcb": 2, for example aabcbaa. It always equals n minus the longest palindromic subsequence: 5 − 3 = 2.
Remember this
- "Is this piece a palindrome?" asked for many pieces → build
pal[i][j]once, then each question is one lookup. - Substring → a yes/no from the inside cell. Subsequence → a number; a mismatch drops one end.
- Split into palindromes → a 1-D DP over prefixes on top of the table; the choice is the last piece.
- Trap: filling
ifrom left to right reads rowi + 1before it exists. Go by length, orifrom the right. - Whenever a problem asks about palindromic pieces of one string many times over, it's this table.
Practise it on Palindromic Substrings, then Longest Palindromic Substring (keep the longest yes), Longest Palindromic Subsequence (a length, not a yes/no), Minimum Insertion Steps to Make a String Palindrome (a cost), Palindrome Partitioning (the table as a lookup while listing splits) and Palindrome Partitioning II.
Watch it work, line by line
Longest Palindromic Substring ↗, s = "babad" → "bab" ("aba" is equally long, but comes later). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is the question about pieces that read the same both ways, and does each palindrome contain a smaller palindrome in its middle I could reuse instead of re-checking?
Reach for it when
- +palindromic substrings/subsequences
- +minimum cuts into palindromes
- +n up to ~2000 for O(n2); larger needs manacher
It fails when
- ×n up to ~1e6, O(n²) too slowuse Manacher, O(n)
- ×Palindrome queries with updates to the stringuse Rolling hash + segment tree
Looks like it, isn't (and the other way round)
- Palindrome Partitioning II looks like Backtracking, needs this pattern
Only the minimum cut is needed: palindrome table + 1D cut DP.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why are there 2n − 1 centres, not n?Reveal
n letters for odd-length palindromes, plus n − 1 gaps between letters for even-length ones like "abba".
2In the table form, why does i run from n − 1 down to 0?Reveal
pal[i][j]needspal[i + 1][j − 1], which is in the row below. Going down (or by increasing length) makes it ready first.3How do the substring and subsequence recurrences differ?Reveal
Substring: a yes/no, ends match AND inside is a palindrome. Subsequence: a length, ends match gives inside + 2, otherwise drop one end and take the max.
Practice ladder
- 1Palindromic Substringscount themMedium
- 2Longest Palindromic Substringthe hookMedium
- 3Longest Palindromic SubsequencesubsequenceMedium
- 4Minimum Insertion Steps to Make a String Palindromecost to fixHard
- 5Palindrome Partitioningtable as a lookupMedium
- 6Palindrome Partitioning IItable under a cut DPHard
- 7Longest Palindromea million lettersMedium
- 8All Palindromescount themHard
Finished Palindromic Substrings? Mark it done and Lessgo moves you to the next step.