Number of positions where a letter can be inserted such that a string becomes palindrome
Last Updated :
20 Jul, 2022
Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome.
Examples:
Input : str = "abca"
Output : possible palindromic strings:
1) acbca (at position 2)
2) abcba (at position 4)
Hence, the output is 2.
Input : str = "aaa"
Output : possible palindromic strings:
1) aaaa
2) aaaa
3) aaaa
4) aaaa
Hence, the output is 4.
Naive Approach: This approach is to insert all 26 alphabets at every position possible i.e., N+1 positions and check at every position if this insertion makes it a palindrome and increase the count.
Efficient Approach: First you have to observe that we have to make insertion only at the point when the character at that point violates the palindrome condition i.e., S[i] != S[N-i-1] . Now, there will be Two cases based on the above fact:
Case I: What if the given string is already a palindrome
Then we can only insert at the position such that the insertion does not violate the palindrome.
- If the length is even then we can always insert any letter in the middle.
- If the length is odd then we can insert the letter which is in middle, to the left or right to it.
- In both the cases we can insert the letter which is in middle(let it be 'CH'), at positions equals to:
(no.of consecutive CH's to the left of middle letter)*2.
Case II: If it is not a palindrome
As mentioned above we should start inserting at position where S[i] != S[N-1-i] , So we increase the count and check for the cases if insertion at any other position makes it a palindrome.
- If S[i]...S[N-i-2] is a palindrome, then we can insert* at any position before S[i] until S[K] != S[N-i-1] , K in range [i-1, 0] .(*letter = S[N-i-1])
- If S[i+1]...S[N-i-1] is a palindrome, then we can insert* at any position after S[n-i-1] until S[K] != S[i] , K in range [N-i, N-1] .(*letter = S[i])
In all the cases we keep increasing the count.
Implementation:
C++
// CPP code to find the no.of positions where a
// letter can be inserted to make it a palindrome
#include <bits/stdc++.h>
using namespace std;
// Function to check if the string is palindrome
bool isPalindrome(string &s, int i, int j)
{
int p = j;
for (int k = i; k <= p; k++) {
if (s[k] != s[p])
return false;
p--;
}
return true;
}
int countWays(string &s)
{
// to know the length of string
int n = s.length();
int count = 0;
// if the given string is a palindrome(Case-I)
if (isPalindrome(s, 0, n - 1))
{
// Sub-case-III)
for (int i = n / 2; i < n; i++)
{
if (s[i] == s[i + 1])
count++;
else
break;
}
if (n % 2 == 0) // if the length is even
{
count++;
count = 2 * count + 1; // sub-case-I
} else
count = 2 * count + 2; // sub-case-II
} else {
for (int i = 0; i < n / 2; i++) {
// insertion point
if (s[i] != s[n - 1 - i])
{
int j = n - 1 - i;
// Case-I
if (isPalindrome(s, i, n - 2 - i))
{
for (int k = i - 1; k >= 0; k--) {
if (s[k] != s[j])
break;
count++;
}
count++;
}
// Case-II
if (isPalindrome(s, i + 1, n - 1 - i))
{
for (int k = n - i; k < n; k++) {
if (s[k] != s[i])
break;
count++;
}
count++;
}
break;
}
}
}
return count;
}
// Driver code
int main()
{
string s = "abca";
cout << countWays(s) << endl;
return 0;
}
Java
// Java code to find the no.of positions where a
// letter can be inserted to make it a palindrome
import java.io.*;
class GFG {
// Function to check if the string is palindrome
static boolean isPalindrome(String s, int i, int j)
{
int p = j;
for (int k = i; k <= p; k++) {
if (s.charAt(k) != s.charAt(p))
return false;
p--;
}
return true;
}
static int countWays(String s)
{
// to know the length of string
int n = s.length();
int count = 0;
// if the given string is a palindrome(Case-I)
if (isPalindrome(s, 0, n - 1)) {
// Sub-case-III)
for (int i = n / 2; i < n; i++) {
if (s.charAt(i) == s.charAt(i + 1))
count++;
else
break;
}
if (n % 2 == 0) // if the length is even
{
count++;
count = 2 * count + 1; // sub-case-I
}
else
count = 2 * count + 2; // sub-case-II
}
else {
for (int i = 0; i < n / 2; i++) {
// insertion point
if (s.charAt(i) != s.charAt(n - 1 - i)) {
int j = n - 1 - i;
// Case-I
if (isPalindrome(s, i, n - 2 - i)) {
for (int k = i - 1; k >= 0; k--) {
if (s.charAt(k) != s.charAt(j))
break;
count++;
}
count++;
}
// Case-II
if (isPalindrome(s, i + 1, n - 1 - i)) {
for (int k = n - i; k < n; k++) {
if (s.charAt(k) != s.charAt(i))
break;
count++;
}
count++;
}
break;
}
}
}
return count;
}
// Driver code
public static void main(String[] args)
{
String s = "abca";
System.out.println(countWays(s));
}
}
// This code is contributed by vt_m.
Python 3
# Python 3 code to find the no.of positions
# where a letter can be inserted to make it
# a palindrome
# Function to check if the string
# is palindrome
def isPalindrome(s, i, j):
p = j
for k in range(i, p + 1):
if (s[k] != s[p]):
return False
p -= 1
return True
def countWays(s):
# to know the length of string
n = len(s)
count = 0
# if the given string is a palindrome(Case-I)
if (isPalindrome(s, 0, n - 1)) :
# Sub-case-III)
for i in range(n // 2, n):
if (s[i] == s[i + 1]):
count += 1
else:
break
if (n % 2 == 0): # if the length is even
count += 1
count = 2 * count + 1 # sub-case-I
else:
count = 2 * count + 2 # sub-case-II
else :
for i in range(n // 2) :
# insertion point
if (s[i] != s[n - 1 - i]) :
j = n - 1 - i
# Case-I
if (isPalindrome(s, i, n - 2 - i)) :
for k in range(i - 1, -1, -1):
if (s[k] != s[j]):
break
count += 1
count += 1
# Case-II
if (isPalindrome(s, i + 1, n - 1 - i)) :
for k in range(n - i, n) :
if (s[k] != s[i]):
break
count += 1
count += 1
break
return count
# Driver code
if __name__ == "__main__":
s = "abca"
print(countWays(s))
# This code is contributed by ita_c
C#
// C# code to find the no. of positions
// where a letter can be inserted
// to make it a palindrome.
using System;
class GFG {
// Function to check if the
// string is palindrome
static bool isPalindrome(String s, int i,
int j)
{
int p = j;
for (int k = i; k <= p; k++)
{
if (s[k] != s[p])
return false;
p--;
}
return true;
}
static int countWays(String s)
{
// to know the length of string
int n = s.Length;
int count = 0;
// if the given string is
// a palindrome(Case-I)
if (isPalindrome(s, 0, n - 1)) {
// Sub-case-III)
for (int i = n / 2; i < n; i++) {
if (s[i] == s[i + 1])
count++;
else
break;
}
// if the length is even
if (n % 2 == 0)
{
count++;
// sub-case-I
count = 2 * count + 1;
}
else
// sub-case-II
count = 2 * count + 2;
}
else {
for (int i = 0; i < n / 2; i++) {
// insertion point
if (s[i] != s[n - 1 - i]) {
int j = n - 1 - i;
// Case-I
if (isPalindrome(s, i, n - 2 - i)) {
for (int k = i - 1; k >= 0; k--) {
if (s[k] != s[j])
break;
count++;
}
count++;
}
// Case-II
if (isPalindrome(s, i + 1, n - 1 - i)) {
for (int k = n - i; k < n; k++) {
if (s[k] != s[i])
break;
count++;
}
count++;
}
break;
}
}
}
return count;
}
// Driver code
public static void Main()
{
String s = "abca";
Console.Write(countWays(s));
}
}
// This code is contributed by nitin mittal
PHP
<?php
// PHP code to find the no. of
// positions where a letter can
// be inserted to make it a palindrome
// Function to check if the
// string is palindrome
function isPalindrome($s, $i, $j)
{
$p = $j;
for ($k = $i; $k <= $p; $k++)
{
if ($s[$k] != $s[$p])
return false;
$p--;
}
return true;
}
function countWays($s)
{
// to know the length of string
$n = strlen($s);
$count = 0;
// if the given string is
// a palindrome(Case-I)
if (isPalindrome($s, 0, $n - 1))
{
// Sub-case-III)
for ($i = $n / 2; $i < $n; $i++)
{
if ($s[$i] == $s[$i + 1])
$count++;
else
break;
}
// if the length is even
if ($n % 2 == 0)
{
$count++;
// sub-case-I
$count = 2 * $count + 1;
}
else
// sub-case-II
$count = 2 * $count + 2;
}
else
{
for ($i = 0; $i < $n / 2; $i++)
{
// insertion point
if ($s[$i] != $s[$n - 1 - $i])
{
$j = $n - 1 - $i;
// Case-I
if (isPalindrome($s, $i, $n - 2 - $i))
{
for ($k = $i - 1; $k >= 0; $k--)
{
if ($s[$k] != $s[$j])
break;
$count++;
}
$count++;
}
// Case-II
if (isPalindrome($s, $i + 1,$n - 1 - $i))
{
for ($k = $n - $i; $k < $n; $k++)
{
if ($s[$k] != $s[$i])
break;
$count++;
}
$count++;
}
break;
}
}
}
return $count;
}
// Driver code
$s = "abca";
echo countWays($s) ;
// This code is contributed by nitin mittal
?>
JavaScript
<script>
// Javascript code to find the no.of positions where a
// letter can be inserted to make it a palindrome
function isPalindrome(s,i,j)
{
let p = j;
for (let k = i; k <= p; k++)
{
if (s[k] != s[p])
return false;
p--;
}
return true;
}
// Function to check if the string is palindrome
function countWays(s)
{
// to know the length of string
let n = s.length;
let count = 0;
// if the given string is a palindrome(Case-I)
if (isPalindrome(s, 0, n - 1))
{
// Sub-case-III)
for (let i = n / 2; i < n; i++)
{
if (s[i] == s[i + 1])
count++;
else
break;
}
if (n % 2 == 0) // if the length is even
{
count++;
count = 2 * count + 1; // sub-case-I
} else
count = 2 * count + 2; // sub-case-II
} else {
for (let i = 0; i < n / 2; i++) {
// insertion point
if (s[i] != s[n - 1 - i])
{
let j = n - 1 - i;
// Case-I
if (isPalindrome(s, i, n - 2 - i))
{
for (let k = i - 1; k >= 0; k--) {
if (s[k] != s[j])
break;
count++;
}
count++;
}
// Case-II
if (isPalindrome(s, i + 1, n - 1 - i))
{
for (let k = n - i; k < n; k++) {
if (s[k] != s[i])
break;
count++;
}
count++;
}
break;
}
}
}
return count;
}
// Driver code
let s = "abca";
document.write( countWays(s));
// This code is contributed by avanitrachhadiya2155
</script>
Similar Reads
Palindrome String Coding Problems
A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Palindrome String
Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome
Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read