Palindromic Substrings
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given a string s, return how many of its substrings are palindromes.
Understand the problem
- A palindrome reads the same forwards and backwards. A substring is a contiguous run of characters.
- Every single character counts as a palindrome.
- Substrings at different positions count separately, even if they contain the same text: in
"aaa", the two"aa"s (positions 0-1 and 1-2) count as two.
Example 1
Input: s = "abc"
Output: 3Only the single letters: "a", "b", "c".
Example 2
Input: s = "aaa"
Output: 6"a" three times, "aa" twice, and "aaa" once: 3 + 2 + 1 = 6.
Example 3
Input: s = "aba"
Output: 4"a", "b", "a", and "aba".
Constraints
1 <= s.length <= 1000scontains lowercase English letters.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Expand outward from every possible center (each character and each gap between characters), and count one palindrome for every step where both sides still match.
The naive approach (and why it's slow)
Check every substring: about n²/2 of them, each taking up to n steps to check. That's O(n³).
The key insight
This is Longest Palindromic Substring asking a different question. The same tool works: expand around every center.
- Every palindrome is symmetric around exactly one center: a character (odd length, like
"aba") or a gap between two characters (even length, like"abba"). - Expanding from a center, every successful step is a new palindrome: from the center of
"cabac"you get"b", then"aba", then"cabac".
So: try all 2n - 1 centers, expand each as far as it goes, and add 1 for every successful step. Each palindrome is counted exactly once, from its own center.
Step by step
s = "aaa" (indexes 0 to 2). The 5 centers:
| Center | Expansions that work | Palindromes found | Count |
|---|---|---|---|
a (index 0) | "a", then the edge | "a" | 1 |
| gap 0 | 1 | "aa", then the edge | "aa" | 1 |
a (index 1) | "a", then "aaa", then the edge | "a", "aaa" | 2 |
| gap 1 | 2 | "aa", then the edge | "aa" | 1 |
a (index 2) | "a", then the edge | "a" | 1 |
Total: 6.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n²).
2n - 1centers, each expanding up ton/2times. - Memory: O(1).
Common mistakes
- Forgetting the gaps. Only expanding around characters misses every even-length palindrome, like the
"aa"s. - Counting only the longest palindrome per center. Every step of the expansion is its own palindrome.
- Counting by distinct text.
"aa"at two different positions counts twice.
Going deeper
The DP view also works here: a table isPal[i][j] is true when s[i] === s[j] and isPal[i+1][j-1] is true. Count the true cells. It's O(n²) time like the expansion, but O(n²) memory, so expanding around centers is usually the better choice.
Reference solution
/**
* @param {string} s
* @return {number}
*/
export default function countSubstrings(s) {
let count = 0
// 2n - 1 centers: even values are a character (odd-length palindromes),
// odd values are the gap between two characters (even-length palindromes).
for (let center = 0; center < 2 * s.length - 1; center++) {
let left = Math.floor(center / 2)
let right = left + (center % 2)
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++ // both sides match: s[left..right] is one more palindrome
left-- // grow outward by one on each side
right++
}
}
return count
}export default function countSubstrings(s: string): number {
let count = 0
// 2n - 1 centers: even values are a character (odd-length palindromes),
// odd values are the gap between two characters (even-length palindromes).
for (let center = 0; center < 2 * s.length - 1; center++) {
let left = Math.floor(center / 2)
let right = left + (center % 2)
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++ // both sides match: s[left..right] is one more palindrome
left-- // grow outward by one on each side
right++
}
}
return count
}def count_substrings(s: str) -> int:
count = 0
# 2n - 1 centers: even values are a character (odd-length palindromes),
# odd values are the gap between two characters (even-length palindromes).
for center in range(2 * len(s) - 1):
left = center // 2
right = left + center % 2
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1 # both sides match: s[left..right] is one more palindrome
left -= 1 # grow outward by one on each side
right += 1
return count