Hello Programmers, In this post, you will learn how to solve HackerRank Palindrome Index Solution. This problem is a part of the HackerRank Algorithms Series.
One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

HackerRank Palindrome Index Solution
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.
Note: The custom checker logic for this challenge is available.
HackerRank Palindrome Index Solution in C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static int read_int() { int ret; scanf("%d", &ret); return ret; } /* caller should free the memory */ static int *read_int_array(int n) { int *ret = malloc(n * sizeof(int)); for (int i = 0; i < n; ++i) { scanf("%d", ret + i); } return ret; } static int intcomp(const void *v1, const void *v2) { return *(const int *)v1 - *(const int *)v2; } static int is_palindrome(const char *s, int len) { /* assert(len > 0); */ /* assert(s); */ if (!s || len <= 0) { return 0; } for (const char *start = s, *end = s + len - 1; start < end; start++, end--) { if (*start != *end) { return 0; } } return 1; } static int so(const char *s, int len, int current_index) { /* assert(len >= 1); */ if (len < 1) { return 0; } while (1) { if (len == 1 || len == 2) { return current_index; } char start = s[0]; char end = s[len - 1]; if (start != end) { /* we have to remove either one */ /* test [start + 1, end] */ if (is_palindrome(s + 1, len - 1)) { return current_index; } else { return current_index + len - 1; } } else { /* return so(s + 1, len - 2, current_index + 1); */ s ++; len -= 2; current_index ++; } } } static int solve(const char *s) { return so(s, strlen(s), 0); } int main(int argc, char *argv[]) { int t = read_int(); /* assert(is_palindrome("aba", 3) == 1); */ /* assert(is_palindrome("abc", 3) == 0); */ /* assert(is_palindrome("a", 1) == 1); */ /* assert(is_palindrome("ab", 2) == 0); */ /* assert(is_palindrome("aa", 2) == 1); */ /* assert(is_palindrome("abba", 4) == 1); */ for (int i = 0; i < t; ++i) { char buf[100010]; scanf(" %s", buf); printf("%d\n", solve(buf)); } return 0; }
HackerRank Palindrome Index Solution in Cpp
#include<stdio.h> #include<string.h> char a[1000005]; char b[1000005]; int is(char *a, int n){ int i; for(i=0;i<n/2;i++)if(a[i]!=a[n-1-i])return i; return -1; } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%s",&a); int l = strlen(a); int x = is(a,l); if(x==-1){ printf("-1\n"); } else { int i; int j=0; for(i=0;a[i];i++){ if(i!=x)b[j++] = a[i]; } if(is(b,l-1)==-1)printf("%d\n",x); else printf("%d\n",l-1-x); } } }
HackerRank Palindrome Index Solution in Java
import java.io.*; public class Solution { public static void solve(Input in, PrintWriter out) throws IOException { int tests = in.nextInt(); for (int test = 0; test < tests; ++test) { String s = in.next(); int i = 0, j = s.length() - 1; while (i < j && s.charAt(i) == s.charAt(j)) { ++i; --j; } int ans; if (i >= j) { ans = -1; } else if (palindrome(s.substring(0, i) + s.substring(i + 1))) { ans = i; } else if (palindrome(s.substring(0, j) + s.substring(j + 1))) { ans = j; } else { throw new AssertionError(s + " " + i + " " + j); } out.println(ans); } } private static boolean palindrome(String s) { int i = 0, j = s.length() - 1; while (i < j && s.charAt(i) == s.charAt(j)) { ++i; --j; } return i >= j; } public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out); out.close(); } static class Input { BufferedReader in; StringBuilder sb = new StringBuilder(); public Input(BufferedReader in) { this.in = in; } public Input(String s) { this.in = new BufferedReader(new StringReader(s)); } public String next() throws IOException { sb.setLength(0); while (true) { int c = in.read(); if (c == -1) { return null; } if (" \n\r\t".indexOf(c) == -1) { sb.append((char)c); break; } } while (true) { int c = in.read(); if (c == -1 || " \n\r\t".indexOf(c) != -1) { break; } sb.append((char)c); } return sb.toString(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
HackerRank Palindrome Index Solution in Python
import sys def main(): t = int(raw_input()) for _ in xrange(t): print palin_index(raw_input()) def palin_index(s): i, j = 0, len(s)-1 while i < j: if s[i] != s[j]: if is_palin(s, i+1, j): return i else: return j i += 1 j -= 1 return -1 def is_palin(s, a, b): while a < b: if s[a] != s[b]: return False a += 1 b -= 1 return True if __name__ == "__main__": sys.exit(main())
HackerRank Palindrome Index Solution using JavaScript
'use strict'; function solve(S) { var mid = Math.floor(S.length / 2); var idx = -1; for (var i = 0, j = S.length - 1; i < mid; i++, j--) { if (S[i] != S[j]) { if (idx == -1) { idx = i; j++; continue; } else { idx = S.length - 1 - idx; break; } } } return idx; } function processData(input) { var parse_fun = function (s) { return parseInt(s, 10); }; var lines = input.split('\n'); var T = parse_fun(lines.shift()); for (var t = 0; t < T; t++) { var S = lines[t].trim().split(''); console.log(solve(S)); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });
HackerRank Palindrome Index Solution in Scala
object Solution { val in = { val lines = scala.io.Source.stdin.getLines lines map (_ split ' ' filter (_.nonEmpty)) flatten } def main(args: Array[String]): Unit = { val testCount = in.next.toInt for (_ <- 1 to testCount) { val S = in.next val N = S.size if (S == S.reverse) println(-1) else { var i = 0 var found = false while (i < N && !found) { if (S(i) != S(N - i - 1)) { val s1 = ((0 until N) filter (_ != i) map S).mkString val s2 = ((0 until N) filter (_ != N - i - 1) map S).mkString if (s1 == s1.reverse) { found = true println(i) } else if (s2 == s2.reverse) { found = true println(N - i - 1) } } i += 1 } } } } }
HackerRank Palindrome Index Solution in Pascal
program Solution; uses sysutils, strutils; var t, i: byte; s : AnsiString; function ispalindrome(s : AnsiString) : boolean; begin ispalindrome := (ReverseString(s) = s); end; function index(s : AnsiString) : LongInt; var start, end1 : Longword; begin start := 1; end1 := length(s); while((start < end1) and (s[start] = s[end1])) do begin Inc(start); Dec(end1); end; if ispalindrome(s) then index := -1 else if (s[start] = s[end1 -1]) and (s[start+1] = s[end1-2]) then index := end1-1 else index := start-1; end; BEGIN readln(t); for i:=1 to t do begin readln(s); writeln(index(s)); end; END.
Disclaimer: This problem (Palindrome Index) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.