#647
Palindromic Substrings
MediumTwo PointersStringDynamic ProgrammingTwo PointersDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
The optimal solution uses a center expansion technique, where we treat each character (and the space between characters) as potential centers of palindromes. This allows us to count palindromic substrings in linear time by expanding around each center.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a count variable to 0.
- 2Step 2: Loop through each character in the string as a potential center.
- 3Step 3: For each center, expand outwards while the characters match, counting palindromes.
solution.py16 lines
1# Full working Python code
2
3def count_palindromic_substrings(s):
4 count = 0
5 n = len(s)
6 for center in range(2 * n - 1):
7 left = center // 2
8 right = left + center % 2
9 while left >= 0 and right < n and s[left] == s[right]:
10 count += 1
11 left -= 1
12 right += 1
13 return count
14
15# Example usage
16print(count_palindromic_substrings('abc')) # Output: 3ℹ
Complexity note: The time complexity is O(n²) because we potentially expand around each character for palindromes, but we do not store any additional data structures, keeping space complexity at O(1).
- 1Palindromic substrings can be counted by expanding around potential centers.
- 2Every single character is a palindrome, contributing to the count.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.