Skip to content
TheCScience
TheCScience
  • Engineering Subjects
    • Human Values
    • Computer System Architecture
    • Digital Communication
    • Internet of Things
  • NCERT Solutions
    • Class 12
    • Class 11
  • HackerRank solutions
    • HackerRank Algorithms Problems Solutions
    • HackerRank C solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
TheCScience
TheCScience

HackerRank Palindrome Index Problem Solution

Yashwant Parihar, April 27, 2023May 6, 2023

In this post, we will solve HackerRank Palindrome Index Problem 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
8 = “bcbc”
Either remove ‘b’ at index 0 or ‘c’ at index 3.
Function Description
Complete the palindromeIndex function in the editor below. palindromelndex 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.

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.

HackerRank Palindrome Index Problem Solution
HackerRank Palindrome Index Problem Solution

Palindrome Index C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>

void check(char *string, int size) {    
    int mid = size >>1;       
    int offendingIndex = -1;    
    for(int i = 0 ; i < mid; i++) {
        if(*(string + i) != *(string +size - 1 -i)) {
            offendingIndex = i;            
            break;
        }
    }
    
    mid = (size -1) >> 1;
    bool isPal = true;
    int head = 0;
    for(int i = 0 ; i <= mid; i++) {
        if(head == offendingIndex) {
            ++head;
        }
                
        if(*(string + head++) != *(string +size - 1 -i)) {
            isPal = false;            
            break;
        }
    }
    
    if(!isPal) {        
        offendingIndex = size -1 -offendingIndex;
    } 

    printf("%d\n",offendingIndex);
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    
    int T;
    
    scanf("%d", &T);
    
    char *strings[T];
    int sizes[T];
    for(int i = 0; i < T; i++) {
        strings[i] = (char*) malloc(sizeof(char) * 100005 );
        scanf("%s", strings[i]);
        sizes[i] = strlen(strings[i]);        
    }
    
    for(int i = 0; i < T; i++) {
        check(strings[i], sizes[i]);        
    }
    return 0;
}

Palindrome Index C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

// check if S[i...j] is a palindrome
// returns mismatched index or -1
int check(const std::string& S, int i, int j) {
    while (i < j) {
        if (S[i] != S[j])
            return i;
        ++i;
        --j;
    }
    return -1;
}

int main() {
    int T; std::cin >> T;
    for (int t = 0; t < T; ++t) {
        std::string S; std::cin >> S;
        int mismatch = check(S, 0, S.size()-1);
        if (mismatch != -1) {
            int i = mismatch;
            int j = S.size()-1-i;
            // need to remove either i or j
            if (check(S, i+1, j) == -1) {
                mismatch = i;
            } else if (check(S, i, j-1) == -1) {
                mismatch = j;
            } else {
                // no valid solution
                mismatch = -1;
            }
        }
        std::cout << mismatch << std::endl;
    }
    return 0;
}

Palindrome Index C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        
        int questionCount = Convert.ToInt32(Console.ReadLine());
        int[] answers = new int[questionCount];
        
        for (int i = 0; i < questionCount; i++)
        {
            answers[i] = solve(Console.ReadLine());
        }    
        
        for (int i = 0; i < questionCount; i++) Console.WriteLine(answers[i]);
    }
    
    public static int solve(string s) {
        for (int i = 0; i < (s.Length + 1) / 2; i++)
        {
            int l = i;
            int r = s.Length - l - 1;
            
            if (s[l] != s[r]) if (s[l+1] == s[r] && s[l+2] == s[r-1]) return l; else return r;
        }
        
        return -1;
    }
}

Palindrome Index Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'palindromeIndex' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts STRING s as parameter.
     */

    public static int palindromeIndex(String s) {
    // Write your code here

        int l = s.length();
        int i,j,a,b;
        for (i=0, j=l-1; i<l; i++,j--){
            if (s.charAt(i)!=s.charAt(j))
                break;
        }
        if (i>j) return -1;

        for (a = i+1, b = j;a<j && b>i+1; a++,b--){
            if (s.charAt(a)!=s.charAt(b))
                return j;
        }
        return i;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, q).forEach(qItr -> {
            try {
                String s = bufferedReader.readLine();

                int result = Result.palindromeIndex(s);

                bufferedWriter.write(String.valueOf(result));
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Palindrome Index JavaScript Solution

function processData(input) {
    //Enter your code here
    var lines = input.split(RegExp("\n", "g"));
    var numCases = parseInt(lines[0]);
    
    for(var i = 0; i < numCases; i++){
        
        // Get current line
        var str = lines[i+1];
        
        var arr = str.split("");
        
        var found = false;
        
        // Iterate from End and Start
        for(var j = 0; j < arr.length/2; j++){
            var start = j;
            var end = arr.length - 1 - j;
            
            if(arr[start] != arr[end]){
                
                if(arr[start] == arr[end-1] && arr[start+1] == arr[end-2]){
                    console.log(end);
                    found = true;
                    break;
                }
                else if(arr[start+1] == arr[end]){
                    console.log(start);
                    found = true;
                    break;
                }
            }
        }
        
        if(found == false){
            console.log(-1);
        }
        
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Palindrome Index Python Solution

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

def palindrome_index(s):
    if palindrome(s):
        return -1
  
    for c in range(len(s)//2):
        if s[c] != s[-(c+1)]:
            if palindrome(s[:c]+s[c+1:]):
                return c
            else:
                return len(s)-(c+1)
    
def main():
    test_count = int(input())
    for _ in range(test_count):
        print(palindrome_index(input()))
        
main()

Other Solution

  • HackerRank Fraudulent Activity Notifications
  • HackerRank Anagram Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

TheCScience

We at TheCScience.com are working towards the goal to give free education to every person by publishing in dept article about Secondary, Senior-Secondary, and Graduation level subjects.

Pages

About US

Contact US

Privacy Policy

DMCA

Engineering Subjects

Internet of Things

Human Values

Digital Communication

Computer System Architecture

Programming Tutorials

Data Structure and Algorithm

C

Java

NCERT

Class 12th

©2026 TheCScience | WordPress Theme by SuperbThemes