00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each successful expansion step around a centre is exactly one new palindrome, so the count is simply the total number of successful steps over all 2n - 1 centres.

Approaches

Both approaches look at every possible palindrome. Expanding around centres needs no table; the DP version marks every palindromic substring.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. A string like "aaaa" has n(n + 1) / 2 palindromic substrings, so counting them one by one is inherently quadratic in the worst case.

Interview Tips and Recommended Approach

  • Count positions, not distinct texts. "aaa" has 6 palindromic substrings, though only 3 distinct ones.
  • Include even centres. Missing them loses every even-length palindrome.
  • Reuse the expansion helper. Returning the number of steps makes counting a one-line change.
  • Mention Manacher's algorithm for an O(n) solution if the interviewer asks for better.

Recommended Approach: Expand Around Center

Why: it counts every palindrome exactly once with constant extra memory, and it shares its core with the longest palindromic substring solution.