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 check two parts of a string are palindrome or not in Python
Suppose we have two strings S and T of same length, we have to check whether it is possible to cut both strings at a common point so that the first part of S and the second part of T form a palindrome.
So, if the input is like S = "cat" T = "dac", then the output will be True, as if we cut the strings into "c" + "at" and "d" + "ac", then "c" + "ac" is a palindrome.
Algorithm
To solve this, we will follow these steps ?
n := size of string a
i := 0
-
while i
i := i + 1
return true when a[from index i to n-i-1] is palindrome or b[from index i to n-i-1] is palindrome
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, a, b):
n = len(a)
i = 0
while i < n and a[i] == b[-i-1]:
i += 1
palindrome = lambda s: s == s[::-1]
return palindrome(a[i:n-i]) or palindrome(b[i:n-i])
ob = Solution()
S = "cat"
T = "dac"
print(ob.solve(S, T))
True
How It Works
The algorithm works by finding the longest common prefix-suffix match between the two strings. It compares characters from the start of string a with characters from the end of string b. Once it finds a mismatch, it checks if the remaining middle portion of either string forms a palindrome.
Step-by-Step Example
Let's trace through the example with S = "cat" and T = "dac" ?
def trace_example():
S = "cat"
T = "dac"
n = len(S)
i = 0
print(f"Strings: S = '{S}', T = '{T}'")
print(f"Length: {n}")
# Check prefix-suffix matching
while i < n and S[i] == T[-i-1]:
print(f"Match found: S[{i}] = '{S[i]}' == T[{-i-1}] = '{T[-i-1]}'")
i += 1
print(f"Final i = {i}")
# Check remaining parts
remaining_S = S[i:n-i]
remaining_T = T[i:n-i]
print(f"Remaining part of S: '{remaining_S}'")
print(f"Remaining part of T: '{remaining_T}'")
palindrome_S = remaining_S == remaining_S[::-1]
palindrome_T = remaining_T == remaining_T[::-1]
print(f"Is remaining S palindrome? {palindrome_S}")
print(f"Is remaining T palindrome? {palindrome_T}")
print(f"Result: {palindrome_S or palindrome_T}")
trace_example()
Strings: S = 'cat', T = 'dac' Length: 3 Match found: S[0] = 'c' == T[-1] = 'c' Final i = 1 Remaining part of S: 'a' Remaining part of T: 'a' Is remaining S palindrome? True Is remaining T palindrome? True Result: True
Conclusion
This algorithm efficiently checks if two strings can be cut at a common point to form a palindrome by combining their parts. The time complexity is O(n) where n is the length of the strings.
