Similar Problems
Similar Problems not available
Split Two Strings To Make Palindrome - Leetcode Solution
Companies:
LeetCode: Split Two Strings To Make Palindrome Leetcode Solution
Difficulty: Medium
Topics: string two-pointers
The problem statement asks us to determine if it is possible to split two given strings, A and B, into two parts, such that when we concatenate them in any order, we can form a palindrome. In other words, we need to determine if there exists an index i such that the two strings can be split at index i, into A[0:i] and A[i:], B[0:i] and B[i:], such that the concatenation of the two parts in any order forms a palindrome.
Here is the algorithm to solve this problem:
- First, we concatenate the two strings A and B and store the result in a variable called S.
- Now, we need to find an index i such that S[0:i] is a palindrome. We start by initializing i to the length of S and decrementing it until we find a palindrome. We can easily check if a string is a palindrome by comparing it with its reverse, which can be obtained using S[::-1].
- Once we find the palindrome S[0:i], we need to check if the other parts of S can also form palindromes. We check this by comparing S[i:] with its reverse and S[:i] with its reverse. If both are palindromes, we return True as we were successfully able to split A and B into parts such that their concatenation forms a palindrome.
- If we cannot find an i such that S[0:i] is a palindrome, we return False as it is not possible to split the strings in the required way.
Here is the Python code for the above algorithm:
def checkPalindrome(s): return s == s[::-1]
def checkPalindromeFormation(A: str, B: str) -> bool: S = A + B n = len(S) i = n while i > 0: i -= 1 if checkPalindrome(S[:i]): break return (checkPalindrome(S[:i]) and checkPalindrome(S[i:])) or (checkPalindrome(S[i:]) and checkPalindrome(S[:i]))
We start by defining a helper function called checkPalindrome, which takes a string as input and returns True if it is a palindrome and False otherwise.
The main function checkPalindromeFormation takes two strings A and B as input and returns True or False depending on whether we can split them in the required way to form a palindrome or not. We concatenate A and B and store the result in S.
We then initialize i to the length of S and decrement it until we find a palindrome in S[0:i]. We store this index in i.
Finally, we check if both S[i:] and S[:i] are palindromes or not. If both are palindromes, we return True as we have successfully found a way to split A and B, such that their concatenation forms a palindrome. If not, we return False.
Overall, the time complexity of this algorithm is O(n^2) as we are essentially checking all possible splits of the concatenated string S. However, the actual time complexity would be lower in practice as we expect to find a palindrome relatively quickly.
Split Two Strings To Make Palindrome Solution Code
1