LeetCode #647 Medium

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²).

Constraints
  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.
stringtwo pointersexpand around centrecounting
Open on LeetCode ↗
02

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.
How to spot this pattern

Counting or finding palindromic substrings is a centre-expansion job: every palindrome is a shorter palindrome with one matching letter added on each side.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def countSubstrings(self, s: str) -> int:
▶3 n = len(s)
▶4 count = 0
▶5 for c in range(2 * n - 1):
▶6 l, r = c // 2, c // 2 + c % 2
▶7 while l >= 0 and r < n and s[l] == s[r]:
▶8 count += 1
▶9 l -= 1
▶10 r += 1
▶11 return count
centresa0b1b2a3count0palindromes countednone yet7 centres: 4 letters + 3 gaps
n4
centres72n − 1
Every palindrome has exactly one middle: a letter if its length is odd, a gap between two letters if it is even. So the 7 dots are the only places a palindrome can grow from, and each palindrome belongs to exactly one dot.
centresa0l rb1b2a3count1palindromes countedaone letter “a” is a palindrome, count 1
l0
r0
count1
New centre at letter 0. A single letter always reads the same both ways, so it counts. Count it now, then widen by one letter on each side.
centresendla0b1rb2a3count1palindromes countedaleft side ran off the start → next centre
l-1
r1
count1
Growing one more step would need a letter before index 0, and there is none. Every palindrome around this centre is already counted, so move on.
centresa0lb1rb2a3count1palindromes counteda“a” ≠ “b” → next centre
l0
r1
count1
New centre at the gap between 0 and 1. The two ends differ, so “ab” is not a palindrome. Any wider window around this centre keeps these same two letters inside it at mirror positions, so it cannot be one either. Stop here.
centresa0b1l rb2a3count2palindromes countedabone letter “b” is a palindrome, count 2
l1
r1
count2
New centre at letter 1. A single letter always reads the same both ways, so it counts. Count it now, then widen by one letter on each side.
centresa0lb1b2ra3count2palindromes countedab“a” ≠ “b” → next centre
l0
r2
count2
The two ends differ, so “abb” is not a palindrome. Any wider window around this centre keeps these same two letters inside it at mirror positions, so it cannot be one either. Stop here.
centresa0b1lb2ra3count3palindromes countedabbbends match → “bb” is a palindrome, count 3
l1
r2
count3
New centre at the gap between 1 and 2. The inside is empty and both ends are “b”, so “bb” is a palindrome too. Count it now, then widen by one letter on each side.
centresa0lb1b2a3rcount4palindromes countedabbbabbaends match → “abba” is a palindrome, count 4
l0
r3
count4
The inside “bb” was already a palindrome and both ends are “a”, so “abba” is a palindrome too. Count it now, then widen by one letter on each side.
centresendla0b1b2a3endrcount4palindromes countedabbbabbaleft side ran off the start → next centre
l-1
r4
count4
Growing one more step would need a letter before index 0, and there is none. Every palindrome around this centre is already counted, so move on.
centresa0b1b2l ra3count5palindromes countedabbbabbabone letter “b” is a palindrome, count 5
l2
r2
count5
New centre at letter 2. A single letter always reads the same both ways, so it counts. Count it now, then widen by one letter on each side.
centresa0b1lb2a3rcount5palindromes countedabbbabbab“b” ≠ “a” → next centre
l1
r3
count5
The two ends differ, so “bba” is not a palindrome. Any wider window around this centre keeps these same two letters inside it at mirror positions, so it cannot be one either. Stop here.
centresa0b1b2la3rcount5palindromes countedabbbabbab“b” ≠ “a” → next centre
l2
r3
count5
New centre at the gap between 2 and 3. The two ends differ, so “ba” is not a palindrome. Any wider window around this centre keeps these same two letters inside it at mirror positions, so it cannot be one either. Stop here.
centresa0b1b2a3l rcount6palindromes countedabbbabbabaone letter “a” is a palindrome, count 6
l3
r3
count6
New centre at letter 3. A single letter always reads the same both ways, so it counts. Count it now, then widen by one letter on each side.
centresa0b1b2la3endrcount6palindromes countedabbbabbabaright side ran off the end → next centre
l2
r4
count6
Growing one more step would need a letter after index 3, and there is none. Every palindrome around this centre is already counted, so move on.
centresa0b1b2a3count6palindromes countedabbbabbabaanswer: 6
count6
All 7 centres are done. Each tile is a different start and end position, so every “b” tile counts even though they spell the same thing. The answer is 6.
05

Common pitfalls

Expanding only from letters

✗ Wrong
for i in range(n):
    l, r = i, i
✓ Right
for c in range(2 * n - 1):
    l, r = c // 2, c // 2 + c % 2

Even-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

✗ Wrong
while l >= 0 and r < n and s[l] == s[r]:
    l -= 1
    r += 1
count += 1
✓ Right
while l >= 0 and r < n and s[l] == s[r]:
    count += 1
    l -= 1
    r += 1

One 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

✗ Wrong
seen.add(s[l:r + 1])
...
return len(seen)
✓ Right
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

✗ Wrong
while s[l] == s[r] and l >= 0 and r < n:
✓ Right
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.

06

Edge cases

Every letter the same, e.g. "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.

No palindromes longer than one letter, e.g. "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.

07

Complexity

Time
O(n²)
Space
O(1)
There are 2n − 1 centres and each grows at most about n / 2 steps. Only l, r and the count are stored.
08

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.