- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Suppose we have two strings S1 and S2 of same lengths, we have to find an index i such that S1[0…i] and S2[i+1…n-1] give a palindrome when they are concatenated together. When it is not possible, return -1.

So, if the input is like S1 = "pqrsu", S2 = "wxyqp", then the output will be 1 as S1[0..1] = "pq", S2[2..n-1] = "ypq", then S1 + S2 = "pqyqp" indicates is a palindrome.

To solve this, we will follow these steps −

n := size of str1

str := blank string

for i in range 0 to n, do

str := str concatenate str1[i]

temp := blank string

for j in range i + 1 to n, do

temp := temp concatenate str2[j]

if isPalindrome(str concatenate temp) is true, then

return i

return -1

## Example

Let us see the following implementation to get better understanding −

def isPalindrome(s): if s == s[::-1]: return True return False def find_index(str1, str2): n = len(str1) str = "" for i in range(n): str = str + str1[i] temp = "" for j in range(i + 1, n): temp += str2[j] if (isPalindrome(str + temp)): return i return -1 str1 = "pqrsu" str2 = "wxyqp" print(find_index(str1, str2))

## Input

"pqrsu", "wxyqp"

## Output

1

- Related Questions & Answers
- Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated in C++
- Program to find number of ways we can arrange letters such that each prefix and suffix have more Bs than As in Python
- Check if suffix and prefix of a string are palindromes in Python
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two in C++
- Program to find longest prefix that is also a suffix in C++
- Rearrange an array such that arr[i] = i in C++
- Count of pairs of (i, j) such that ((n % i) % j) % n is maximized in C++
- Program to find number of pairs (i, j) such that ith and jth elements are same in Python
- match_results prefix() and suffix() in C++
- Count of unique pairs (arr[i], arr[j]) such that i < j in C++
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K in C++
- Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j] in C++
- When should I use a composite index in MySQL?
- Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix in C++
- Count pairs (i,j) such that (i+j) is divisible by both A and B in C++

Advertisements