Palindrome Index

  • + 0 comments

    Easy Solution with Javascript

    function palindromeIndex(str) {
        // check if the string is already a palindrome
     if (isPalindrome(str)) {
       return -1;
     }
     // 
     for (let i = 0; i < Math.floor(str.length/2); i++) {
        let newStr = str.slice(0, i) + str.slice(i + 1);
        if (isPalindrome(newStr)) {
            return i;
        }
       if(str[i]!=str[str.length-1-i]){
        return isPalindrome(str.slice(0,str.length-1-i)+str.slice(str.length-i))?str.length-1-i:-1;
       }
      
     }
     return -1;
    }
    
    // helper function to check if a string is a palindrome
    function isPalindrome(str) {
     let palindrom=true;
     let i=0;
     while(i<Math.floor(str.length/2) && palindrom){
         palindrom=str[i]==str[str.length-i-1]
         i++;
     }
     return palindrom
    }