#1616
Split Two Strings to Make Palindrome
MediumTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach leverages the properties of palindromes by checking the longest matching prefix of one string with the suffix of the other. This reduces unnecessary checks and speeds up the process.
⚙️
Algorithm
4 steps- 1Step 1: Define a helper function to check if a substring is a palindrome.
- 2Step 2: Check for each possible split index if the prefix of one string matches the suffix of the other.
- 3Step 3: If a match is found, check if the remaining parts form a palindrome.
- 4Step 4: Return true if any valid split forms a palindrome; otherwise, return false.
solution.py8 lines
1def isPalindrome(s): return s == s[::-1]
2
3def checkPalindromeFormation(a, b):
4 n = len(a)
5 for i in range(n + 1):
6 if a[:i] == b[-i:][::-1] or b[:i] == a[-i:][::-1]:
7 return True
8 return Falseℹ
Complexity note: The time complexity is O(n) because we only iterate through the strings once, checking for matching prefixes and suffixes. The space complexity is O(n) due to the string manipulations.
- 1Understanding palindromes is crucial; they read the same forwards and backwards.
- 2Matching prefixes and suffixes can significantly reduce the number of checks needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.