In this Palindrome Index HackerRank solution, Given a string of lowercase letters in the range ascii[a-z], determine the index of a character that can be removed to make the string a palindrome. There may be more than one solution, but any will do. If the word is already a palindrome or there is no solution, return -1. Otherwise, return the index of a character to remove.
Example
Either remove ‘b’ at index or ‘c’ at index .
Function Description
Complete the palindromeIndex function in the editor below.
palindromeIndex has the following parameter(s):
- string s: a string to analyze
Returns
- int: the index of the character to remove or
Input Format
The first line contains an integer , the number of queries.
Each of the next lines contains a query string .
Constraints
- All characters are in the range ascii[a-z].
Sample Input
STDIN Function
----- --------
3 q = 3
aaab s = 'aaab' (first query)
baa s = 'baa' (second query)
aaa s = 'aaa' (third query)
Sample Output
3
0
-1
Explanation
Query 1: “aaab”
Removing ‘b’ at index results in a palindrome, so return .
Query 2: “baa”
Removing ‘b’ at index results in a palindrome, so return .
Query 3: “aaa”
This string is already a palindrome, so return . Removing any one of the characters would result in a palindrome, but this test comes first.
Note: The custom checker logic for this challenge is available here.
Palindrome Index HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C
int string_length (char* str)
{
int len;
for(len = 0; str[len]; len++);
return len;
}
int palindromeIndex(char* s)
{
int len = string_length(s);
for (int counter = 0; counter < len/2; counter++)
{
if (s[counter] != s[len - 1 - counter])
{
if (s[counter] == s[len - 2 - counter])
{
if (s[counter + 1] == s[len - 3 - counter])
{
return len - 1 - counter;
}
}
return counter;
}
}
return -1;
}
Problem Solution in Python
def palindromeIndex(s):
if s == s[::-1]:
return -1
for i in range(len(s)//2):
if s[i] != s[len(s) - 1 - i]:
newstr = s[:i] + s[i+1:]
if newstr == newstr[::-1]:
return i
newstr = s[:len(s) - i - 1]+ s[len(s)-i:]
if newstr == newstr[::-1]:
return len(s) - i - 1
return -1
Problem Solution in C++
bool isPalindrome(string s){
string r = s;
reverse(r.begin(), r.end());
return s == r;
}
int palindromeIndex(string input) {
int s, e;
for(s = 0, e = input.size() - 1; s < e; s++, e--){
if(input[s] != input[e]) break;
}
if(s >= e) return -1;
string s1 = input, s2 = input;
s1.erase(s1.begin() + s);
if(isPalindrome(s1)) return s;
s2.erase(s2.begin() + e);
if(isPalindrome(s2)) return e;
return -1;
}
Leave a Reply