Palindromic Substrings
Palindromic Substrings is LeetCode 647 (Medium). Given a string s, return how many of its substrings are palindromes.
- A substring is a contiguous run of letters. A palindrome reads the same forwards and backwards.
- Substrings are counted by position: the same text at two places counts twice, and every single letter counts.
s has up to 1,000 letters, so testing every substring on its own (O(n³)) is too slow; the target is O(n²).
- 1 <= s.length <= 1000
- s consists of lowercase English letters.
Intuition
Instead of testing substrings one by one, grow every palindrome outward from its middle. A window whose two ends match and whose inside is a palindrome is itself a palindrome, so each step outward that still matches finds one more.
- Centres: the middle is a letter (odd length) or the gap between two letters (even length). A string of n letters has 2n − 1 of them.
- Counting: every matching step is a new palindrome, so add 1 per step, not 1 per centre.
- Stopping: the first mismatch ends that centre. Every wider window keeps the two mismatched letters at mirror positions, so none of them can be a palindrome.
Counting or finding palindromic substrings is a centre-expansion job: every palindrome is a shorter palindrome with one matching letter added on each side.
Approach
Before reading on, decide where a palindrome can have its middle, and what a palindrome of length k tells you about the window of length k + 2 around it. Aim for O(n²) time and O(1) extra space.
Walk all 2n − 1 centres
Number the centres c = 0 … 2n − 2. An even c is the letter at c // 2; an odd c is the gap just after it. Starting from l = c // 2 and r = l + c % 2 covers both kinds in one loop, so no centre is skipped.
Count while the ends match
While l and r are inside the string and s[l] == s[r], the window from l to r is a palindrome, because its inside matched on the previous step. Add 1 to the count for every such step, then move l one left and r one right.
Stop at the first mismatch or edge
When the two ends differ, or a pointer leaves the string, move on to the next centre. No wider window around this centre can be a palindrome, so stopping here skips nothing.
Why the total is exact
A palindrome has exactly one middle, so it is found from exactly one centre, on exactly one step. Summing the steps over all centres therefore counts each one once, with no set of seen strings and only O(1) extra space.
Code in Python, C++ and Java
Common pitfalls
Expanding only from letters
for i in range(n):
l, r = i, ifor c in range(2 * n - 1):
l, r = c // 2, c // 2 + c % 2Even-length palindromes have their middle in a gap. For "abba" the letter-only loop returns 4 instead of 6, because "bb" and "abba" are never tried.
Adding 1 per centre instead of per step
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
count += 1while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1One centre can hold several palindromes of growing width. For "aaa" the middle letter gives "a" and "aaa", so counting per centre returns 5 instead of 6.
Counting distinct strings
seen.add(s[l:r + 1]) ... return len(seen)
count += 1
The problem counts positions, not different texts. For "aaa" a set holds only "a", "aa" and "aaa", giving 3 instead of 6.
Comparing letters before the bounds check
while s[l] == s[r] and l >= 0 and r < n:
while l >= 0 and r < n and s[l] == s[r]:
For "a", after the first match r becomes 1 and s[1] raises an IndexError in Python (and reads out of bounds in C++). The bounds test must come first so it short-circuits.
Edge cases
"aaaa"Every window is a palindrome, so the answer is n(n + 1) / 2 = 10. This is also the slowest input, since every centre grows until it hits the edge of the string.
"abc"Each letter centre counts once and each gap fails straight away, so the answer is n = 3. The answer is never less than n.
Complexity
l, r and the count are stored.Palindromic Substrings FAQ
How is this different from Longest Palindromic Substring?
Both grow windows from the same 2n − 1 centres. Longest Palindromic Substring (LeetCode 5) keeps only the widest window it reaches; this problem adds 1 at every matching step. The loops are almost the same; only what you record changes.
Can it be solved with dynamic programming?
Yes. Let dp[i][j] be true when s[i..j] is a palindrome: the ends match and dp[i + 1][j - 1] is true (or the window has at most 2 letters). Fill it by increasing length and count the true cells. That is also O(n²) time, but it needs an n × n table.
Is there an O(n) way to count them?
Manacher's algorithm finds the widest palindrome at every centre in linear time, reusing mirror results inside the widest palindrome seen so far. Once the widest palindrome at a centre is known, the number of palindromes around that centre is half its length, rounded up, so summing those halves gives the count. With n at most 1,000 it is rarely expected.