Magicsheet logo

Split Two Strings to Make Palindrome

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Split Two Strings to Make Palindrome

What is this problem about?

In the Split Two Strings to Make Palindrome interview question, you are given two strings aa and bb of the same length. You need to check if there exists an index ii such that either aprefix+bsuffixa_{prefix} + b_{suffix} or bprefix+asuffixb_{prefix} + a_{suffix} forms a palindrome. The split must happen at the same index for both strings.

Why is this asked in interviews?

This is a classic Google interview question that tests your proficiency with the Two Pointers interview pattern and your ability to identify symmetry. It requires a clean, modular approach to avoid redundant code and handle the logic for both aprefix+bsuffixa_{prefix} + b_{suffix} and bprefix+asuffixb_{prefix} + a_{suffix} efficiently.

Algorithmic pattern used

The algorithm uses the Two Pointers technique. You compare the characters of aa from the start and bb from the end. As long as they match, you move the pointers inward. When you find a mismatch at indices ll and rr, the only way to form a palindrome is if the remaining middle portion of either string aa or string bb (from ll to rr) is itself a palindrome.

Example explanation (use your own example)

Let a="abcde"a = "abcde" and b="fghba"b = "fghba".

  1. Compare a[0]a[0] ('a') and b[4]b[4] ('a'). They match.
  2. Compare a[1]a[1] ('b') and b[3]b[3] ('b'). They match.
  3. Compare a[2]a[2] ('c') and b[2]b[2] ('h'). Mismatch! Now, check if the middle of aa ("c") or the middle of bb ("h") is a palindrome. Both are! So, aprefix+bsuffixa_{prefix} + b_{suffix} (where we take "ab" from aa and "hba" from bb) results in "abhba", which is a palindrome.

Common mistakes candidates make

  • Brute Force: Trying every possible split point, which leads to O(N2)O(N^2) and a Time Limit Exceeded error.
  • Missing the "other" case: Only checking aprefix+bsuffixa_{prefix} + b_{suffix} and forgetting bprefix+asuffixb_{prefix} + a_{suffix}.
  • Complex logic: Writing one giant function instead of a helper function to check if a substring is a palindrome.
  • Off-by-one errors: Incorrectly calculating the indices for the middle substring check.

Interview preparation tip

Always look for ways to reuse code. In this Split Two Strings to Make Palindrome coding problem, the logic for both combinations is nearly identical. Write a generic function that takes two strings and checks the condition, then call it twice with the arguments swapped.

Similar Questions