Palindrome Index – HackerRank Solution

In this post, we will solve Palindrome Index HackerRank Solution. This problem (Palindrome Index) is a part of HackerRank Problem Solving series.

Task

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

s = “bcbc”

Either remove ‘b’ at index 0 or ‘c’ at index 3.

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 -1

Input Format

The first line contains an integer q, the number of queries.
Each of the next q lines contains a query string s.

Constraints

  • 1 <= q <= 20
  • 1 <= length of s <= 105 + 5
  • 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 3 results in a palindrome, so return 3.

Query 2: “baa”
Removing ‘b’ at index 0 results in a palindrome, so return 0.

Query 3: “aaa”
This string is already a palindrome, so return -1. Removing any one of the characters would result in a palindrome, but this test comes first.

Solution – Palindrome Index – HackerRank Solution

C++

#include<iostream>
#include<string>
using namespace std;

bool ispalin(string str)
{
    int i = 0, j = str.length() - 1;
    while (i < j)
    {
        if (str[i] != str[j]) return false;
        i++, j--;
    }
    return true;
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        string str;
        cin >> str;
        int i = 0, len = str.length(), j = len - 1;
        int ans = -1;
        while (i < j && str[i] == str[j]) i++, j--;
        if (i < j)
        {
            string str1 = str.substr(0, i) + str.substr(i + 1, str.length() - i - 1);
            if (ispalin(str1)) ans = i;
            string str2 = str.substr(0, j) + str.substr(j + 1, str.length() - j - 1);
            if (ispalin(str2)) ans = j;
        }
        cout << ans << endl;
    }
    return 0;
}

Python

#!/bin/python3

import sys
from collections import Counter

def is_palindrome(s):
    return s == s[::-1]

def palindromeIndex(s):
    ret = -1
    lens = len(s)
    ind = 0
    
    if is_palindrome(s):
        return ret
    
    while ind < lens//2:
        if s[ind] != s[lens-ind-1]:
            if s[ind+1] == s[lens-ind-1] and s[ind+2] == s[lens-ind-2]:
                ret = ind
                break
            else:
                ret = lens-ind-1
                break
        ind += 1
    
    return ret
    

q = int(input().strip())
for a0 in range(q):
    s = input().strip()
    result = palindromeIndex(s)
    print(result)

Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int palindromeIndex(String s){
        for(int x=0;x<=(s.length()-1)/2;x++)
        {   
            if(s.charAt(x)!=s.charAt(s.length()-1-x))
            {
                if(s.charAt(x+1)==s.charAt(s.length()-1-x)&&s.charAt(x+2)==s.charAt(s.length()-2-x))
                {
                    return x;
                }
                if(s.charAt(x)==s.charAt(s.length()-2-x))
                {
                    return s.length()-x-1;
                }
            }
        }
        return -1;
        // Complete this function
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String s = in.next();
            int result = palindromeIndex(s);
            System.out.println(result);
        }
    }
}

Note: This problem (Palindrome Index) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *