Split Two Strings to Make Palindrome - Problem

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. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c", and "abc" + "" are valid splits.

Return true if it is possible to form a palindrome string, otherwise return false.

Input & Output

Example 1 — Basic Valid Case
$ Input: a = "x", b = "y"
Output: true
💡 Note: Split at position 0: aprefix="" + bsuffix="y" = "y" (palindrome), or split at position 1: aprefix="x" + bsuffix="" = "x" (palindrome)
Example 2 — Valid Combination
$ Input: a = "xbdef", b = "xecab"
Output: false
💡 Note: No split position creates a palindrome: splitting anywhere produces non-palindromic combinations
Example 3 — Another Valid Case
$ Input: a = "ulacfd", b = "jizalu"
Output: true
💡 Note: Split at position 3: aprefix="ula" + bsuffix="alu" = "ulaalu" (palindrome)

Constraints

  • 1 ≤ a.length, b.length ≤ 105
  • a.length == b.length
  • a and b consist of lowercase English letters

Visualization

Tap to expand
Split Two Strings to Make Palindrome INPUT String a "x" String b "y" Length: 1 (same) Split at index 0 or 1: "" + "x" "x" + "" "" + "y" "y" + "" ALGORITHM STEPS 1 Two-Pointer Init left=0, right=len-1 2 Check Combination 1 a_prefix + b_suffix 3 Check Combination 2 b_prefix + a_suffix 4 Verify Palindrome Check middle section For length=1: idx=0: "" + "y" = "y" idx=1: "x" + "" = "x" Single char = palindrome! FINAL RESULT Split at index 0: a_prefix + b_suffix: "" + "y" = "y" b_prefix + a_suffix: "" + "x" = "x" Palindrome Check: "y" = "y" [OK] "x" = "x" [OK] Output: true Key Insight: For single-character strings, any split results in either the original char or empty string. A single character is always a palindrome (reads same forwards and backwards). The optimal approach uses two pointers to check both combinations efficiently in O(n) time. TutorialsPoint - Split Two Strings to Make Palindrome | Optimal Solution
Asked in
Facebook 25 Google 20
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen