#1616
Medium Algorithms Split two strings to make palindrome
Two Pointers String
32.1% acceptance
Feb 25, 2026
778
260
You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty.
Return true if it is possible to form a palindrome string, otherwise return false.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn check_palindrome_formation(a: String, b: String) -> bool {
let a: Vec<u8> = a.bytes().collect();
let b: Vec<u8> = b.bytes().collect();
Self::check(&a, &b) || Self::check(&b, &a)
}
fn check(a: &[u8], b: &[u8]) -> bool {
let n = a.len();
let mut l = 0;
let mut r = n - 1;
while l < r && a[l] == b[r] {
l += 1;
r -= 1;
}
// middle part: check if a[l..=r] or b[l..=r] is palindrome
Self::is_palindrome(a, l, r) || Self::is_palindrome(b, l, r)
}
fn is_palindrome(s: &[u8], mut l: usize, mut r: usize) -> bool {
while l < r {
if s[l] != s[r] { return false; }
l += 1;
r -= 1;
}
true
}
}