Palindromic Substrings

Medium

Topics
StringDynamic ProgrammingTwo Pointers

Given a string s, return the number of palindromic substrings in it. Substrings at different start or end positions count separately even if identical.

Example 1

a0b1c2
Every single character is already a palindrome, so the count starts at 3 and grows from there to 3. Expanding from each of the 2n−1 centres counts each one exactly once, with no substring ever built or compared as a whole.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "abc"
Output: 3
Explanation: The three single characters.

Example 2

a0a1a2
Input:  s = "aaa"
Output: 6

Constraints

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every palindrome has a center — either a single character (odd length) or a gap between two characters (even length). Expanding outward from each of the 2n-1 centers finds all palindromes without recomputation.

Approach

  1. For each index, expand around the odd center (i, i) and the even center (i, i+1).
  2. While the two ends match, count one palindrome and widen.
  3. Sum the counts over all centers.

Dry Run

s = "aaa". There are 2n - 1 = 5 centres, not 3.
  centre 0   odd, both at index 0          finds "a"              total 1
  centre 1   even, gap between 0 and 1     finds "aa"             total 2
  centre 2   odd, both at index 1          finds "a", then "aaa"  total 4
  centre 3   even, gap between 1 and 2     finds "aa"             total 5
  centre 4   odd, both at index 2          finds "a"              total 6
answer 6
Centre 2 is the one that earns its keep: it finds two palindromes, "a" and then
"aaa", because each successful expansion is itself a distinct substring and gets
counted on the way out. The count is incremented inside the while loop, not after
it.
The `left = center // 2` and `right = left + center % 2` pair is what folds both
parities into one loop. Even centres get right = left + 1, which starts the
expansion straddling a gap; odd centres get right = left, starting on a single
character.
Use only the n odd centres and every even-length palindrome is lost: "aaa" gives
4 instead of 6, missing both copies of "aa".

Complexity

  • Time — O(n^2): each of the ~2n centers can expand up to n times.
  • Space — O(1): only pointers and a counter.

Common Pitfalls

  • There are 2n - 1 centres, not n. Every gap between two characters is a centre too, and skipping them loses every even-length palindrome: aaa gives 4 instead of 6.
  • left = center // 2 and right = left + center % 2 is the trick that folds both cases into one loop -- even centres get right = left + 1, odd centres get right = left.

Full Solution — all languages

class Solution:
    def countSubstrings(self, s):
        res=0
        for center in range(2*len(s)-1):
            left=center//2
            right=left+center%2
            while left>=0 and right<len(s) and s[left]==s[right]:
                res+=1
                left-=1
                right+=1
        return res
SensAI
Beta
Tap the mic to stop voice mode