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.

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 *