Skip to content
Problem 647 · LeetCode 647(opens in a new tab)

Palindromic Substrings

MediumDynamic programming

You get a string s of lower-case letters. Count how many of its substrings are palindromes, meaning they read the same from left to right as from right to left.

A substring is a run of neighbouring letters. Substrings at different positions count separately, even when they spell the same thing: in "aa" the two single letters are two different substrings.

Example 1

Input:  s = "abba"
Output: 6
Why:    "a", "b", "b", "a", "bb" and "abba"
2 more examples and the constraints

Example 2

Input:  s = "xyz"
Output: 3
Why:    only the single letters

Example 3

Input:  s = "zzzz"
Output: 10
Why:    every one of the 10 substrings is all z

Constraints

  • 1 ≤ length of s ≤ 1,000
  • s holds only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every substringO(n³)
  2. Table of palindromesO(n²)
  3. Expand around centersO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 lettersVerdict
Check every substringO(n³)
Mention it, then move on
Table of palindromesO(n²)
Passes; costs n² memory
Expand around centersO(n²)
Best; same speed, no table

n = length of s.

Edge cases to test

  • One letter. "q" has exactly one palindrome, itself.
  • Even-length palindromes. "abba" needs the gap centers; letter centers alone would miss "bb" and "abba".
  • All the same letter. "zzzz" counts every substring: n(n + 1)/2 = 10.
  • No repeats. "xyz" gives just the n single letters.

Common mistakes

  • Using only letter centers, so even-length palindromes such as "bb" are never counted.
  • Counting distinct palindromes instead of positions: "aa" has 3, not 2.
  • Filling the table with i from 0 upward, so pal[i+1][j−1] is read before it is set.

How to talk through it

  1. 1Clarify. Do repeats at different positions count separately? Is the string only lower-case letters?
  2. 2Give the brute force. Every substring, checked from both ends: O(n³). Say that is too slow for 1,000 letters.
  3. 3Spot the reuse. A palindrome with its ends cut off is still a palindrome; that gives an O(n²) table.
  4. 4Expand from centers. Same rule, read outward from 2n − 1 middles, with no table: O(n²) time, O(1) space.
  5. 5Test out loud. Run "abba" for even lengths, "zzzz" for all-equal, and a single letter.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?