Palindromic SubstringsLoading saved progress…

Palindromic Substrings

A palindrome is a string that reads the same forwards and backwards — "a", "bb", "aba". A substring is a contiguous slice of the input: a start index, an end index, and everything between them. Your job is to count how many of a string's substrings are palindromes.

Crucially, you count by position, not by content. If the same palindrome appears at two different places, both occurrences count. In "aaa", the substring "a" shows up at three different positions, so it contributes 3 to the total — not 1.

Signature

// s: the input string
// returns: how many of s's substrings are palindromes,
//          counting each distinct (start, end) position separately
function stringPalindromicSubstrings(s: string): number;

Examples

stringPalindromicSubstrings('abc');
// → 3
// Each single character is a palindrome: "a", "b", "c". No longer ones.
stringPalindromicSubstrings('aaa');
// → 6
// Three singles "a","a","a", two pairs "aa","aa", one triple "aaa".

Notes

  • Count by position, not by distinct content. "aa" appears twice in "aaa" (positions 0–1 and 1–2). Both count. You are not counting distinct palindromic strings.
  • Single characters always count. Every length-1 substring is trivially a palindrome, so a string of length n contributes at least n.
  • Overlapping substrings count separately. In "aaa", the two "aa" substrings overlap at the middle character. Both still count.
  • The empty string returns 0. It has no substrings.
  • Assume s contains only standard characters; you do not need to handle Unicode normalization or surrogate pairs.
Loading editor…