Palindromic Substrings

35 min · countSubstrings()

The word aaa looks repetitive, but it hides six mirrored slices when positions matter. Three single letters, two copies of aa, and one aaa all count.

Given a lowercase string s, return the number of its palindromic substrings. A substring is one continuous slice of the original string, and a palindrome reads the same from left to right and right to left.

Count positions, not distinct text. If the same letters appear at two different start/end pairs, those are two separate substrings.

Constraints

  • 1 <= s.length <= 1_000
  • s contains only lowercase English letters.
  • The answer is at most s.length * (s.length + 1) / 2, so it fits a 32-bit signed integer.

Hints

Start from intervals

You can choose every pair of boundaries and test whether the slice between them is a palindrome. What repeated work does that create?

Peel matching ends

s[left:right] is palindromic when its end characters match and the interval inside them is also palindromic. That relationship gives you a two-dimensional DP.

Every palindrome has a center

A palindrome grows symmetrically from either one character or the gap between two characters. Count each successful expansion across all 2n - 1 centers.

Follow-up

Can you keep O(n²) time while reducing the extra space from O(n²) to O(1)?

Visible cases

Examples

Example 1

ready
Input
s = "abc"
Expected
3
Why
only the three one-character substrings are palindromes

Example 2

ready
Input
s = "aaa"
Expected
6
Why
three singles, two position-distinct 'aa' slices, and one 'aaa'

Example 3

ready
Input
s = "a"
Expected
1
Why
every single character is a palindrome

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite