Skip to content

Palindromic Substrings

Count every substring that reads the same forwards and backwards, by expanding around each center.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

You get a string s of lowercase letters. Return how many of its substrings are palindromes, reading the same forwards and backwards. Substrings at different positions count separately, even when they hold the same letters.

Input s = "abba"

Output 6

The four single letters, bb and abba.

Input s = "abcb"

Output 5

The four single letters and bcb.

Key constraint: The string has at most 1,000 letters, so O(n^2) work is fine.

How to spot the pattern

  • You count substrings with a mirror property.
  • Every palindrome is a smaller palindrome with one matching letter added on each side.

The idea

DP state: pal(i, j) is true when s[i..j] is a palindrome, and pal(i, j) = (s[i] == s[j]) and pal(i + 1, j - 1). So the palindromes that share a center are nested: each one is the previous one with a letter added at each end. Expanding outward from each of the 2n - 1 centers walks exactly these states, and every successful step is one more palindrome to count.

Brute force: Check each of the O(n^2) substrings for being a palindrome, which takes O(n^3) time.

Step by step

  1. 1For each index, try two centers: on the letter for odd lengths and in the gap after it for even lengths.
  2. 2Set lo and hi to the center.
  3. 3While both are inside the string and s[lo] == s[hi], add 1 to the count and move lo left and hi right.
  4. 4Return the count after all centers are done.

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        count = 0
        for center in range(n):
            # odd lengths sit on one letter, even lengths between two letters
            for lo, hi in ((center, center), (center, center + 1)):
                # s[lo..hi] is a palindrome when s[lo] == s[hi] and s[lo + 1..hi - 1] is one,
                # so every successful step outward finds one more palindrome
                while lo >= 0 and hi < n and s[lo] == s[hi]:
                    count += 1
                    lo -= 1
                    hi += 1
        return count

Complexity

Time

O(n^2)

Space

O(1)

There are 2n - 1 centers, each expanding at most n / 2 steps.

Watch out for

  • Skipping even-length centers, which misses palindromes like bb.
  • Counting different palindromes instead of positions: aa has 3 palindromic substrings (a, a and aa), not 2.

Follow-up questions

Can you do it with a table?

Yes: fill pal[i][j] for i from n - 1 down to 0 and count the true cells. The time is the same, but it needs O(n^2) memory.

Can it be done in O(n)?

Manacher's algorithm finds the longest palindrome around every center in O(n) total. A center whose longest palindrome has length L holds (L + 1) / 2 of them, rounded down, so you add those up.

In Hinglish

Har center se bahar failao; jitni baar dono kinaaron ke letters match karein, utne palindrome mile. Odd aur even dono tarah ke center lena mat bhoolna.

Related problems