Skip to content
BytePatterns

Count Palindromic Substrings

MediumStrings#expand-around-center#palindrome~25m

Problem

Given a string s, count its substrings that read the same forwards and backwards. Substrings at different positions count separately even when they spell the same text, and every single character counts as one. Aim for O(n²) time and O(1) extra space.

Examples

Input:  s = "level"
Output: 7
Why:    five single letters, plus "eve" and "level"
Input:  s = "xyz"
Output: 3
Why:    only the single letters
Input:  s = ""
Output: 0
Why:    edge case, an empty string has no substrings to count

Hints

0 / 3

Stuck on the idea rather than the code? Longest Palindromic Substring covers it.