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 split two strings to make palindrome using Python
Given two strings a and b of equal length, we need to find if we can split both strings at the same index to create a palindrome by combining parts from different strings.
We can split string a into a_pref + a_suff and string b into b_pref + b_suff, then check if a_pref + b_suff or b_pref + a_suff forms a palindrome.
Example
If a = "pqrst" and b = "turqp", we can split:
-
a?["pq", "rst"] -
b?["tu", "rqp"]
Then a_pref + b_suff = "pq" + "rqp" = "pqrqp", which is a palindrome.
Algorithm
For each combination (x, y) from [(a, b), (b, a)]:
- Start from both ends and move inward while characters match
- Extract the middle portions that don't match
- Check if either middle portion is a palindrome
Implementation
def solve(a, b):
for x, y in [[a, b], [b, a]]:
i, j = 0, len(x) - 1
# Move pointers while characters match
while i < len(x) and j >= 0 and x[i] == y[j]:
i += 1
j -= 1
# Extract middle portions
midx = x[i:j+1]
midy = y[i:j+1]
# Check if either middle portion is palindrome
if midx == midx[::-1] or midy == midy[::-1]:
return True
return False
# Test the function
a = "pqrst"
b = "turqp"
print(solve(a, b))
True
How It Works
The algorithm works by finding the longest matching prefix-suffix pair between the two possible combinations. The remaining middle portion needs to be a palindrome in at least one of the strings to form a valid split.
Step-by-Step Trace
For a = "pqrst" and b = "turqp":
def solve_with_trace(a, b):
for x, y in [[a, b], [b, a]]:
print(f"Checking x='{x}', y='{y}'")
i, j = 0, len(x) - 1
while i < len(x) and j >= 0 and x[i] == y[j]:
print(f" Match: x[{i}]='{x[i]}' == y[{j}]='{y[j]}'")
i += 1
j -= 1
midx = x[i:j+1]
midy = y[i:j+1]
print(f" Middle portions: midx='{midx}', midy='{midy}'")
if midx == midx[::-1] or midy == midy[::-1]:
print(f" Found palindrome!")
return True
print()
return False
a = "pqrst"
b = "turqp"
result = solve_with_trace(a, b)
print(f"Result: {result}")
Checking x='pqrst', y='turqp' Middle portions: midx='pqrst', midy='turqp' Checking x='turqp', y='pqrst' Match: x[0]='t' == y[4]='t' Match: x[1]='u' == y[3]='s' Middle portions: midx='rq', midy='rs' Result: False
Conclusion
This algorithm efficiently checks if two strings can be split to form a palindrome by examining matching characters from both ends and verifying if the remaining middle portions are palindromes. The time complexity is O(n) where n is the string length.
