Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Palindromic Substrings in Python
A palindromic substring is a substring that reads the same forwards and backwards. Given a string, we need to count all palindromic substrings where substrings with different start or end indices are counted separately, even if they contain the same characters.
For example, in the string "aaa", there are 6 palindromic substrings: "a", "a", "a", "aa", "aa", "aaa".
Brute Force Approach
The simplest approach is to check every possible substring and verify if it's a palindrome ?
class Solution:
def countSubstrings(self, s):
counter = 0
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
temp = s[i:j]
if temp == temp[::-1]:
counter += 1
return counter
# Test the solution
solution = Solution()
print(solution.countSubstrings("aaa"))
print(solution.countSubstrings("abc"))
print(solution.countSubstrings("aba"))
6 3 4
Optimized Expand Around Centers Approach
A more efficient approach expands around each possible center to find palindromes ?
class Solution:
def countSubstrings(self, s):
def expand_around_center(left, right):
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
total_count = 0
for i in range(len(s)):
# Count odd-length palindromes (centered at i)
total_count += expand_around_center(i, i)
# Count even-length palindromes (centered between i and i+1)
total_count += expand_around_center(i, i + 1)
return total_count
# Test the optimized solution
solution = Solution()
print(solution.countSubstrings("aaa"))
print(solution.countSubstrings("abc"))
print(solution.countSubstrings("racecar"))
6 3 10
Comparison
| Approach | Time Complexity | Space Complexity | Description |
|---|---|---|---|
| Brute Force | O(n³) | O(1) | Check every substring |
| Expand Around Centers | O(n²) | O(1) | Expand from each center |
How the Expand Around Centers Works
For each position in the string, we consider it as a potential center and expand outward. We check both odd-length palindromes (single character center) and even-length palindromes (between two characters) ?
# Example walkthrough for "aba"
s = "aba"
# Position 0: 'a'
# Odd center at 0: "a" (1 palindrome)
# Even center between 0,1: no palindromes
# Position 1: 'b'
# Odd center at 1: "b", "aba" (2 palindromes)
# Even center between 1,2: no palindromes
# Position 2: 'a'
# Odd center at 2: "a" (1 palindrome)
print(f"Total palindromic substrings in '{s}': 4")
Total palindromic substrings in 'aba': 4
Conclusion
The brute force approach is simple but inefficient with O(n³) complexity. The expand around centers method is more optimal with O(n²) time complexity and is the preferred solution for counting palindromic substrings.
