Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated in Python

Given two strings S1 and S2 of the same length, we need to find an index i such that the prefix S1[0...i] and suffix S2[i+1...n-1] form a palindrome when concatenated. If no such index exists, return -1.

For example, with S1 = "pqrsu" and S2 = "wxyqp", we find that S1[0..1] = "pq" and S2[2..4] = "yqp" combine to form "pqyqp", which is a palindrome at index 1.

Algorithm

To solve this problem, we follow these steps ?

  • Initialize n as the length of both strings

  • For each index i from 0 to n-1:

    • Extract prefix from S1[0...i]

    • Extract suffix from S2[i+1...n-1]

    • Concatenate prefix and suffix

    • Check if the result is a palindrome

    • If yes, return i

  • If no palindrome is found, return -1

Example

Let's implement the solution with a helper function to check palindromes ?

def isPalindrome(s):
    if s == s[::-1]:
        return True
    return False

def find_index(str1, str2):
    n = len(str1)
    
    for i in range(n):
        # Get prefix from str1
        prefix = str1[:i+1]
        
        # Get suffix from str2
        suffix = str2[i+1:]
        
        # Check if concatenation is palindrome
        combined = prefix + suffix
        if isPalindrome(combined):
            return i
    
    return -1

# Test the function
str1 = "pqrsu"
str2 = "wxyqp"
result = find_index(str1, str2)
print(f"Index: {result}")

# Let's trace through the example
print("\nStep-by-step trace:")
for i in range(len(str1)):
    prefix = str1[:i+1]
    suffix = str2[i+1:]
    combined = prefix + suffix
    is_pal = isPalindrome(combined)
    print(f"i={i}: '{prefix}' + '{suffix}' = '{combined}' ? Palindrome: {is_pal}")
Index: 1

Step-by-step trace:
i=0: 'p' + 'xyqp' = 'pxyqp' ? Palindrome: False
i=1: 'pq' + 'yqp' = 'pqyqp' ? Palindrome: True
i=2: 'pqr' + 'qp' = 'pqrqp' ? Palindrome: False
i=3: 'pqrs' + 'p' = 'pqrsp' ? Palindrome: False
i=4: 'pqrsu' + '' = 'pqrsu' ? Palindrome: False

Optimized Approach

We can optimize the palindrome check by comparing characters from both ends ?

def find_index_optimized(str1, str2):
    n = len(str1)
    
    for i in range(n):
        # Build the combined string
        combined = str1[:i+1] + str2[i+1:]
        
        # Check palindrome efficiently
        left, right = 0, len(combined) - 1
        is_palindrome = True
        
        while left < right:
            if combined[left] != combined[right]:
                is_palindrome = False
                break
            left += 1
            right -= 1
        
        if is_palindrome:
            return i
    
    return -1

# Test with different examples
test_cases = [
    ("pqrsu", "wxyqp"),
    ("abc", "def"),
    ("ab", "ba")
]

for str1, str2 in test_cases:
    result = find_index_optimized(str1, str2)
    print(f"'{str1}' + '{str2}' ? Index: {result}")
'pqrsu' + 'wxyqp' ? Index: 1
'abc' + 'def' ? Index: -1
'ab' + 'ba' ? Index: 0

Time Complexity

The time complexity is O(n²) where n is the length of the strings, since we iterate through n positions and for each position, we may check up to n characters for palindrome verification. The space complexity is O(n) for storing the combined string.

Conclusion

This algorithm efficiently finds the index where prefix and suffix concatenation forms a palindrome. The solution iterates through all possible split points and checks each combination for palindrome properties.

Updated on: 2026-03-25T09:41:13+05:30

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements