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
Program to find possible number of palindromes we can make by trimming string in Python
Suppose we have a string s, we have to find the number of ways we can obtain a palindrome by trimming the left and right sides of s. This involves finding all possible palindromic substrings within the given string.
So, if the input is like s = "momo", then the output will be 6. The palindromic substrings are: ["m", "o", "m", "o", "mom", "omo"].
Algorithm Approach
To solve this, we will follow these steps ?
Define a function
expand()that takes parameters i, j, and sInitialize counter c := 0
-
While i >= 0 and j
Expand outward: i := i ? 1, j := j + 1
Increment counter: c := c + 1
Return the count c
From the main method, iterate through each position and check for both odd-length and even-length palindromes
Implementation
def expand(i, j, s):
c = 0
while i >= 0 and j < len(s) and s[i] == s[j]:
i -= 1
j += 1
c += 1
return c
class Solution:
def solve(self, s):
c = 0
for i in range(len(s)):
# Check for odd-length palindromes (center at i)
c += expand(i, i, s)
# Check for even-length palindromes (center between i and i+1)
c += expand(i, i + 1, s)
return c
# Test the solution
ob = Solution()
s = "momo"
print("Number of palindromic substrings:", ob.solve(s))
Number of palindromic substrings: 6
How It Works
The algorithm uses the "expand around centers" approach:
Odd-length palindromes: We consider each character as a potential center and expand outward
Even-length palindromes: We consider the space between two characters as a potential center
For each valid palindrome found, we increment our counter
Example Walkthrough
For the string "momo", the palindromic substrings found are ?
def find_all_palindromes(s):
palindromes = []
def expand_and_collect(i, j, s):
results = []
while i >= 0 and j < len(s) and s[i] == s[j]:
results.append(s[i:j+1])
i -= 1
j += 1
return results
for i in range(len(s)):
# Odd-length palindromes
palindromes.extend(expand_and_collect(i, i, s))
# Even-length palindromes
palindromes.extend(expand_and_collect(i, i + 1, s))
return palindromes
s = "momo"
all_palindromes = find_all_palindromes(s)
print("All palindromic substrings:", all_palindromes)
print("Total count:", len(all_palindromes))
All palindromic substrings: ['m', 'o', 'mom', 'm', 'omo', 'o'] Total count: 6
Time and Space Complexity
Time Complexity: O(n²) where n is the length of the string
Space Complexity: O(1) as we only use a constant amount of extra space
Conclusion
The expand around centers approach efficiently finds all palindromic substrings by checking both odd and even-length palindromes from each position. This method provides an optimal solution with O(n²) time complexity for counting palindromic substrings in a given string.
