Palindromic Substrings

MediumString DP · Expand Around Centre🧩 String DPLeetCode #647 ↗Updated

Problem

Count how many contiguous substrings of s are palindromes. Substrings are counted by position, so equal text at different start/end indices counts more than once.
Inputs = "abc"Output3 (a, b, c)
Inputs = "aaa"Output6 (a, a, a, aa, aa, aaa)

1 ≤ s.length ≤ 1000  ·  lowercase English letters

Try it yourself

Java
class Solution {
    public int countSubstrings(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Each palindrome has exactly one centre (a char or the gap between two chars). Expanding outward from each of the 2n-1 centres, every successful step is one new palindrome — so just count the steps.
PatternString DP

Instinct Two strings compared char by char (match, edit, interleave) means dp[i][j] over prefixes; one string's palindromes or splits means dp[l][r] or dp[i].

Memory hack Match? Go diagonal. Mismatch? Ask the neighbours. Up drops a char from s, left drops one from t, diagonal uses both.

Open the String DP guide →

Approaches

Brute ForceTest Every Substring

Time O(n3)Space O(1)

Enumerate all n(n+1)/2 index pairs (i, j) and check each window with two pointers moving inward. Add one for every palindrome.

Java
public int countSubstrings(String s) {
    int n = s.length(), count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (isPalindrome(s, i, j)) count++;
        }
    }
    return count;
}

private boolean isPalindrome(String s, int l, int r) {
    while (l < r) {
        if (s.charAt(l++) != s.charAt(r--)) return false;
    }
    return true;
}

Straightforward, but re-checks the same inner characters over and over.

At a glance

LevelApproachTimeSpace
Brute ForceTest Every SubstringO(n3)O(1)
Better2-D Palindrome TableO(n2)O(n2)
OptimalExpand Around Every CentreO(n2)O(1)
Common pitfalls
  • Counting distinct palindrome strings instead of positions — "aaa" is 6, not 3.
  • Dropping even-length centres — undercounts strings like "aa".
  • Filling the table top-down by i — pal[i+1][j-1] is not ready yet.
Interview tips
  • Ask whether duplicates by position count — it decides the whole approach.
  • Reuse the centre-expansion helper from Longest Palindromic Substring and say so.
  • State the bound: at most n(n+1)/2 palindromes, so output-driven O(n2) is natural.
Pattern
Expand around centre → count or find contiguous palindromes without extra memory.
My notes saved in this browser