Split Two Strings to Make Palindrome — LeetCode 1616 Python Solution

MediumTwo PointersString
Problem
#1616
Reading time
2 min

The 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.

Example

Input
a = "x", b = "y"
Output
true

Python solution

Python
class Solution:
    def checkPalindromeFormation(self, a: str, b: str) -> bool:
        def check1(a: str, b: str) -> bool:
            i, j = 0, len(b) - 1
            while i < j and a[i] == b[j]:
                i, j = i + 1, j - 1
            return i >= j or check2(a, i, j) or check2(b, i, j)

        def check2(a: str, i: int, j: int) -> bool:
            return a[i : j + 1] == a[i : j + 1][::-1]

        return check1(a, b) or check1(b, a)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1616. Split Two Strings to Make Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1616. Split Two Strings to Make Palindrome?
LeetCode 1616. Split Two Strings to Make Palindrome is rated Medium on LeetCode.
What is the time complexity of LeetCode 1616. Split Two Strings to Make Palindrome?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1616. Split Two Strings to Make Palindrome?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1616. Split Two Strings to Make Palindrome cover?
LeetCode 1616. Split Two Strings to Make Palindrome is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview