Palindromic Substrings

Difficulty: Medium

Given a string s, count how many of its substrings are palindromes. Substrings at different positions count separately, even if the text is the same. For example, in "aaa" the "a" at index 0 and the "a" at index 1 each count.

Examples

Input: s = "abc"
Output: 3

"a", "b", and "c" are each a palindrome on their own; no longer substring is.

Input: s = "aaa"
Output: 6

Three single "a"s, two "aa"s (positions 0-1 and 1-2), and one "aaa".

Constraints

  • 1 <= s.length <= 1000

  • s consists of lowercase English letters

Approach

As in the longest-palindrome problem, each palindromic substring is defined by its center and how far it stretches. Check all 2n - 1 centers (each character and each gap between adjacent characters), and expand while both sides match. Each step of an expansion is exactly one distinct palindromic substring.

So instead of tracking the longest, add 1 to a count on every successful match. After trying every center, the count is the answer.

Solutions

Brute Force — Check Every Substring

Test every substring and count the palindromes.

function countSubstrings(s) {
  function isPalindrome(str) {
    let left = 0;
    let right = str.length - 1;
    while (left < right) {
      if (str[left] !== str[right]) return false;
      left++;
      right--;
    }
    return true;
  }

  let count = 0;
  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      if (isPalindrome(s.slice(i, j + 1))) count++;
    }
  }
  return count;
}

Time: O(n^3) — O(n^2) substrings, each checked in O(n) · Space: O(1) extra, ignoring the substrings themselves

Optimal — Expand Around Center

Try every center (each character and each gap between two characters) and expand while both sides match, counting one palindrome per successful step.

function countSubstrings(s) {
  let count = 0;

  function expand(left, right) {
    while (left >= 0 && right < s.length && s[left] === s[right]) {
      count++;
      left--;
      right++;
    }
  }

  for (let i = 0; i < s.length; i++) {
    expand(i, i);       // odd-length palindromes centered on i
    expand(i, i + 1);   // even-length palindromes centered between i and i+1
  }

  return count;
}

Time: O(n^2) · Space: O(1) extra