InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Palindromic Substrings

medium Original ↗
Solving tips
  • Count by expanding around each of the 2n-1 centers: every successful expansion step is one more palindrome.
  • Expand both (i,i) odd centers and (i,i+1) even centers, or you undercount even palindromes like the 'aa's in 'aaa'.
  • Count distinct positions, not distinct text: 'aaa' has 6 palindromic substrings even though only 2 distinct strings.
  • Target O(n^2) time, O(1) space; the same recurrence as longest-palindrome, and Manacher reaches O(n).

Problem

Given a string s, count how many of its contiguous substrings are palindromes. Substrings at different start/end positions are counted separately even if their text is identical. Every single character counts as a palindrome.

Examples

  • s = "abc"3 — the three single characters "a", "b", "c"; no longer palindrome.
  • s = "aaa"6"a"×3, "aa"×2, "aaa"×1.
  • s = "aba"4"a", "b", "a", and "aba".

Constraints

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

Think about it first

Hint 1 Every substring is either a palindrome or not — brute force checks all O(n²) of them in O(n) each. The sub-question "is s[i..j] a palindrome?" is the thing to speed up.
Hint 2 s[i..j] is a palindrome iff s[i] == s[j] and the inside s[i+1..j-1] is a palindrome (or has length ≤ 1). Fill a 2-D boolean table and count the Trues.
Hint 3 Or count by center: every palindrome has one of 2n-1 centers. Expand from each center outward; each successful expansion step is one more palindrome. O(n²) time, O(1) space.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.