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 number of ways we can split a palindrome in python
Suppose we have a string s, we have to find the number of ways we can partition the string such that each part is a palindrome.
So, if the input is like s = "xyyx", then the output will be 3, as we have splits like: ["x", "yy", "x"], ["x", "y", "y", "x"], ["xyyx"].
Approach
To solve this, we will use dynamic programming with the following steps −
- Create a table of size n + 1 initialized with 0, except table[0] = 1
- For each position i, check all possible substrings ending at i
- If a substring from j to i is a palindrome, add table[j] to table[i]
- Return the last element of the table
Example
class Solution:
def solve(self, s):
n = len(s)
table = [1] + [0] * n
for i in range(n + 1):
for j in range(i):
sub = s[j:i]
if sub == sub[::-1]:
table[i] += table[j]
return table[-1]
ob = Solution()
s = "xyyx"
print(ob.solve(s))
The output of the above code is −
3
How It Works
Let's trace through the algorithm with s = "xyyx" −
def solve_with_trace(s):
n = len(s)
table = [1] + [0] * n
print(f"Initial table: {table}")
for i in range(n + 1):
for j in range(i):
sub = s[j:i]
if sub == sub[::-1]:
print(f"Found palindrome '{sub}' at position {j}:{i}")
table[i] += table[j]
print(f"table[{i}] = {table[i]}")
return table[-1]
s = "xyyx"
result = solve_with_trace(s)
print(f"Total ways: {result}")
Initial table: [1, 0, 0, 0, 0] Found palindrome 'x' at position 0:1 table[1] = 1 Found palindrome 'y' at position 1:2 table[2] = 1 Found palindrome 'yy' at position 1:3 table[3] = 1 Found palindrome 'x' at position 3:4 table[4] = 1 Found palindrome 'xyyx' at position 0:4 table[4] = 2 Total ways: 2
Alternative Implementation
Here's a more readable version with helper function to check palindromes −
def is_palindrome(s):
return s == s[::-1]
def count_palindrome_partitions(s):
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1 # Empty string has one way
for i in range(1, n + 1):
for j in range(i):
substring = s[j:i]
if is_palindrome(substring):
dp[i] += dp[j]
return dp[n]
# Test with multiple examples
test_strings = ["xyyx", "aba", "aab", "raceacar"]
for s in test_strings:
result = count_palindrome_partitions(s)
print(f"String '{s}': {result} ways")
String 'xyyx': 2 String 'aba': 2 String 'aab': 2 String 'raceacar': 3
Time Complexity
The time complexity is O(n³) where n is the length of the string. For each position i (O(n)), we check all substrings ending at i (O(n)), and checking if a substring is palindrome takes O(n) time.
Conclusion
Dynamic programming efficiently counts palindromic partitions by building solutions incrementally. The key insight is that if we know the number of ways to partition a prefix, we can extend it by adding palindromic substrings.
