
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- Program to find longest prefix that is also a suffix in C++
- match_results prefix() and suffix() in C++
- How can I eradicate some specific suffix or prefix or both from a MySQL string?
- Program to find number of pairs (i, j) such that ith and jth elements are same in Python
- Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k] in Python
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two in C++
- When should I use a composite index in MySQL?
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K in C++
- Count of unique pairs (arr[i], arr[j]) such that i < j 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++
- Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i in C++

Advertisements