Header Ad

HackerRank Palindrome Index problem solution

In this HackerRank Palindrome Index problem solution, we have given a string of lowercase letters in the range ascii[a-z], to 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.

HackerRank Palindrome Index problem solution


Problem solution in Python.

def calc_pal(line):

    list = [x for x in line]
    
    orig = list[:]
    rev = list[:]
    rev.reverse()
    
    if orig == rev:
            return -1
       
    for i in range(len(orig)):
        if not orig[i] == rev[i]:
            cpy = orig[:]
            del cpy[i]
            cpyRev = rev[:]
            del cpyRev[len(orig) - i - 1]
            if cpy == cpyRev:
                return i
            else:
                return len(orig) - i - 1

m = int(input().strip())

lines = []
for i in range(m):
    lines.append(input())
    
for line in lines:
    print(calc_pal(line))

Problem solution in Java.

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 {

    

    public static int palindromeIndex(String s) {
    
    char arr[]=s.toCharArray();
    int left=0;
    int right=arr.length-1;
    
    while(left<=right){
        if(arr[left]!=arr[right]){
        boolean Rres=IsPalindrome(arr,left,right-1);
        if(Rres)
        return right;
        else
        {
            boolean Lres=IsPalindrome(arr,left+1,right);
            if(Lres)
            return left;
        }
        
        }
        right--;
        left++;
    }
    return -1;
    }
    public static boolean IsPalindrome(char arr[],int left,int right){
        
        while(left<=right){
            if(arr[left]!=arr[right])
            return false;
            right--;
            left++;
        }
        
        return true;
        
    }

}

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();
    }
}

Problem solution in C++.

#include <stdio.h>
#include <string.h>

char x[120000];

int main()
{
    int cases;
    scanf("%d", &cases);
    
    for (int index = 1; index <= cases; index++)
    {
        scanf("%s", &x);
        int len = strlen(x);
        
        int i, j;
        for (i = 0, j = len - 1; i <= j; i++, j--)
        {
            if (x[i] != x[j])
            {
                int p, q;
                for (p = i + 1, q = j; p <= q; p++, q--)
                {
                    if (x[p] != x[q])
                    {
                        printf("%d\n", j);
                        goto out;
                    }
                }
                printf("%d\n", i);
                out:
                goto end;
            }
        }
        
        printf("%d\n", -1);
        end:;
    }
    
    return 0;
}

Problem solution in C.

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

#define MAX_STRING_LENGTH 100005 

#define TRUE 1
#define FALSE 0

int isPalindrome(char* s) {
  int isPal= TRUE;
  int len = strlen(s);
  int j;
  for (j = 0; j < (len / 2) + 1 && isPal; ++j) {
    if (s[j] != s[len - j - 1]) {
      isPal = FALSE;
    }
  }
  return isPal;
}

int main(void) {

  int i, j;
  int numTestCases;
  char s[MAX_STRING_LENGTH + 1];
  char s1[MAX_STRING_LENGTH + 1];
  int len;

  scanf("%d", &numTestCases);

  for (i = 0; i < numTestCases; ++i) {

    scanf("%s", s);

    if (isPalindrome(s)) {
      printf("-1\n");
      continue;
    }

    s1[0] = '\0';
    len = strlen(s);

    for (j = 0; j < (len / 2) + 1; ++j) {
      if (s[j] != s[len - j - 1]) {
        strncpy(s1, s, j);
        s1[j] = '\0';
        strcat(s1, &s[j + 1]);
        if (isPalindrome(s1)) {
          printf("%d\n", j);
        } else {
          printf("%d\n", len - j - 1);
        }
        break;
      }
    }
  }

  return 0;

}


Post a Comment

0 Comments