InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Palindromic Substrings

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug