KatInterview

Palindromic Substring Counter

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringspalindromestwo-pointersstring-matching

Last updated

Tests ability to identify and count all palindromic substrings using center expansion and understanding of linear-time optimization techniques.

Write a function that takes a string containing only lowercase letters and returns the total number of substrings that read the same forwards and backwards.

Each substring is identified by its starting and ending positions. If the same sequence of characters appears multiple times at different positions, count each occurrence separately.

For instance, in "aaa", there are three single-character substrings ("a" at positions 0, 1, and 2), two two-character substrings ("aa" at positions 0-1 and 1-2), and one three-character substring ("aaa" at position 0-2), for a total of 6.

Constraints

  • 0 ≤ length of string ≤ 1000
  • String contains only lowercase ASCII letters (a-z)
  • Empty string returns 0

Examples

Example 1

Input: count_palindromic_substrings('abc')

Output: 3

Example 2

Input: count_palindromic_substrings('aaa')

Output: 6

Example 3

Input: count_palindromic_substrings('ababa')

Output: 9

Hints

Hint 1

Consider that every palindrome expands symmetrically from a central point - either a single character or the gap between two characters.

Hint 2

For a string of length n, there are n potential single-character centers and n-1 potential between-character centers to check.

Hint 3

The quadratic approach expands outward from each center while characters match. A linear-time solution reuses information from previously computed centers through symmetry properties.