Count Palindromic Substrings by Expanding Around Centers
Quick Overview
Count every contiguous palindromic substring occurrence in a string, treating equal text at different positions as separate results. Include single characters, exclude empty substrings, preserve exact case, and return a 64-bit count.
Count Palindromic Substrings by Expanding Around Centers
Company: Voleon
Role: Site Reliability Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
## Problem
Given a string, count its palindromic substrings. Substrings with equal text but different start or end positions are counted separately.
### Function Contract
Implement `countPalindromicSubstrings(text)`.
### Constraints & Assumptions
- `0 <= len(text) <= 5,000`.
- `text` contains Unicode code points; treating each runtime's character unit consistently is acceptable for the exercise.
- Single-character substrings are palindromes.
- Return a 64-bit integer.
### Clarifying Questions to Ask
- Are subsequences included? No, only contiguous substrings.
- Are duplicate textual substrings counted once? No, count occurrences by position.
- Is the empty substring a palindrome for this count? No.
- Is case folded? No, comparison is exact.
```hint Enumerate centers, not substrings
Every palindrome has either one character or one gap as its unique center. Expand while the two characters match.
```
### Examples
```text
text = "abc"
output = 3
text = "aaa"
output = 6
```
For `"aaa"`, the three length-one, two length-two, and one length-three occurrences all count.
### Evaluation Focus
- Checks all `2n - 1` odd and even centers.
- Counts occurrences rather than distinct values.
- Handles empty input and repeated characters.
- Runs in `O(n^2)` worst-case time with `O(1)` extra space.
### Extensions to Discuss
1. How does Manacher's algorithm reduce the running time to `O(n)`?
2. How would you count only distinct palindromic substrings?
3. What changes when comparison must use Unicode grapheme clusters?
Quick Answer: Count every contiguous palindromic substring occurrence in a string, treating equal text at different positions as separate results. Include single characters, exclude empty substrings, preserve exact case, and return a 64-bit count.