Palindrome Index

  • + 57 comments

    The testcase 11 and 14 are not checking for both correct answer. I have verified it for test case 11. My answer is 8, while that in output file is 44. Both are correct as the indexes are wc and cw being compared and any of c and w can be removed. The string is: hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh

    • + 6 comments

      Same problem here, #11 and #14 are failing!

      • [DELETED] + 1 comment
        [deleted]
        • + 9 comments

          My python logic passed all test cases.

          Hackerrank - Palindrome Index Solution

          My Java Solution

          static int palindromeIndex(String s)
              {
                  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;
              }
          
          • + 0 comments

            This wont work though if the string cant be a palindrome after removing a character , right?

          • + 0 comments

            please explain your logic

          • + 0 comments

            pls explanation your code ??

          • + 0 comments

            Thanx for idea... the improved method body: int l = s.length(); int i,j,a,b; for (i=0, j=l-1; ij) return -1; if (s.charAt(i + 1) == s.charAt(j)) { for (a = i + 1, b = j; a < b; a++, b--) { if (s.charAt(a) != s.charAt(b)) return -1; } return i; } else if (s.charAt(i) == s.charAt(j - 1)) { for (a = i, b = j - 1; a < b; a++, b--) { if (s.charAt(a) != s.charAt(b)) return -1; } return j; } return -1;

          • [deleted]
            + 0 comments
            //I THINK THIS MAY BE READABLE (C++)
                bool palindrome(string s)
             {
             int l=s.size();
             for(int i=0;i<l/2;i++)
              {
               if(s[i]!=s[l-i-1])
               return false;
              }  
             return true;
            }
             int palindromeIndex(string s) {
            int x,y;
             int l=s.size();
            for(int i=0;i<l/2;i++)
              {
            if(s[i]!=s[l-i-1])
            {
                x=i;
                y=l-i-1;
                break;
            }
              }
            s=s.substr(0,x)+s.substr(x+1,s.size());
            if(palindrome(s))
             {
             return x;
             }
             else {
             return y;
             }
              }
            
          • + 0 comments

            This solution is really help me :)

          • + 0 comments

            Your java solution doesn't work.

            for example : aabdefcaa should return -1 you return 6

          • + 1 comment

            both the python and the java solution you gave, did NOT pass MOST of the tests I had.

            • + 0 comments

              I guess there is no test case in hackerrank where a string after removing a character cannot become a palidrome. If there was, the above logic would fail.

      • + 2 comments

        same problem.pls help

        • + 2 comments

          same here...

          • + 5 comments

            If you remove 8th char it is not a palindrome anymore. hgygsvlf (*wnsw) tuhmyaljkqlqjjqlqkjlaymhutws (nwcw) flvsgygh see those inside the bracket above. wnsw-nwcw. whereas, if you remove 44th char, (i.e.) w, then: hgygsvlf (cwns) wtuhmyaljkqlqjjqlqkjlaymhutw (snwc) flvsgygh it becomes pallindrome. Hope this helps.

            • + 14 comments

              No the author is correct with all the test cases. check it out. Used Goto statement here but logic is correct.

              #include<iostream>
              #include<string>
              using namespace std;
              int main(){
                  int r,a;
                  cin>>r;
                  while(r--)
                      {
                          string z;
                          cin>>z;
                          int q=z.size();
                          for( a=0;a<=(q/2);a++)
                              {
                                  if(z[a]!=z[q-1-a])
                                      {
                                           if((z[a+1]==z[q-1-a])&&(z[a+2]==z[q-1-a-1]))
                                          cout<<a<<endl;
                                         else if((z[a]==z[q-1-a-1])&&(z[a+1]==z[q-1-a-2]))
                                          cout<<q-1-a<<endl;
                                          
                                          goto jump;
                                      }
                              }
                              cout<<"-1"<<endl;
                      jump:;
                      }
                  return 0;
              }
              
              • + 0 comments

                yes same problem in test case 11 & 14

              • + 0 comments

                Why use 'goto' when you can use 'break'?

              • + 0 comments

                11th test case worked in my case-

                int check_pal(string s1) {

                int i,k,flag=0; for(i=0,k=s1.length()-1;i<(s1.length())/2 && k>=(s1.length())/2;i++,k--) {

                       if(s1[i]!=s1[k])
                         {  flag=1;
                             return 0;
                           }
                
                     }
                return 1;
                

                } int checked_pal(int j,string s1) {int i,k; for(i=0,k=s1.length()-1;i<(s1.length())/2 && k>=(s1.length())/2;i++,k--) {

                     if(i==j)
                        {i++;}
                      if(k==j)
                         {k--;}
                
                       if(s1[i]!=s1[k])
                         {
                           return 0;
                         }
                
                     }
                
                 return 1;
                

                } int main() { int t,j,i; cin>>t; for(i=1;i<=t;i++) { string s1; cin>>s1; //cout<<"ok--"<<(s1.length()-1)<

                    if(!check_pal(s1))
                    {
                                 for(j=0;j<s1.length();j++)
                                {
                                    if(checked_pal(j,s1))
                                    {flag=1;
                                    cout<<j<<endl;
                                    break;
                                    }
                
                                }
                
                    }
                
                    if(flag==0)
                        cout<<"-1"<<endl;
                }
                
                return 0;
                

                }

              • + 0 comments

                Thanks, That helped me I was using the same logic only I missed "(z[a+2]==z[q-1-a-1])", I passed test case 11 and 14 too after this.

              • + 0 comments

                gorgeous solution

              • + 5 comments
                static int palindromeIndex(String s){
                    	for(int i =0,j =s.length()-1; i<j; i++, j--)
                    		if(s.charAt(i)!=s.charAt(j))
                    			if(isPalindrome(s, i))
                    				return i;
                    			else if(isPalindrome(s, j))
                    					return j;
                    	return -1;
                    }
                    
                    static boolean isPalindrome(String s, int index){
                		for(int i =index+1,j =s.length()-1-index; i<j; i++, j--)
                    		if(s.charAt(i)!=s.charAt(j))
                    			return false;
                		return true;
                	}
                
                • + 0 comments

                  clear solution.

                • + 0 comments

                  You should check is the string palindrome at starting of palindromeIndex as it will reduce all the computation.

                • + 0 comments

                  Wonder how it passed all the test cases. Answer of aaaaabab should it -1. This code will give 7.

                • + 0 comments

                  Readable solution but… time complexity is O()

                • + 0 comments

                  I still confused with the checking part. I don't get how it is going to check all the possibles. 0 1 2 3 4 i from 0 1 j from 4 3

                  when index = 0, check from 1 to 4 index = 4, i > j loop is not going to loop. ?????

                  Therefore, can you explain this to me. Addtionally, Thank You for sharing reduced for loop. I use silmiar idea but I create my own checking function.

                  static boolean check_palindrome1(String s, int index) {
                      for (int i = 0, j = s.length() - 1; i < j;) {
                          if (i == index) {
                              i++;
                          }
                          else if (j == index) {
                              j--;
                          }
                          if (s.charAt(i) != s.charAt(j)) {
                              return false;
                          }
                          else {
                              i++;
                              j--;
                          }
                      }
                      return true;
                  }
                  static int palindromeIndex(String s) {
                      for (int i = 0, j = s.length() - 1; i < j; i++, j--)  {
                          if (s.charAt(i) != s.charAt(j)) {
                              if (check_palindrome1(s,i)) {
                                  return i;
                              }
                              if (check_palindrome1(s,j)) {
                                  return j;
                              }
                          }
                      }
                      return -1;
                  }
                  
              • + 2 comments

                The code is not correct, even though it has passed all given test cases it is wrong.

                EG: aabbtkbbaac your code gives output 10 but infact the answer is "-1"

                • + 1 comment

                  the EG: aabbtkbbaac you have given is wrong, Pls read the question carefully.

                  • + 0 comments

                    Please excuse everything thats wrong with this style of writing code. I'm just an amatuer. But, i did get the right output for your String.

                        static int palindromeIndex(String s){
                            // Complete this function
                            String temp;
                    
                            if(isPali(s)){
                                return -1;
                            }
                    
                            else{
                            for(int i=0;i<s.length();i++){
                                temp=s;
                                System.out.println("before "+temp);
                                temp = temp.substring(0,i)+temp.substring(i+1);
                                System.out.println("after "+temp);
                                if(isPali2(temp))
                                    return i;
                            }
                                return -1;
                         }
                        }
                        static boolean isPali2(String s){
                    
                            StringBuilder sb = new StringBuilder(s);
                            sb.reverse();
                    
                            if(s.equals(sb.toString()))
                                return true;
                    
                            else return false;
                        }
                    
              • + 0 comments

                doesnt work with aacbb

              • + 0 comments

                it is very helpful...!!bro...!!!thanks a lot..!!

              • + 0 comments

                wrong solution! string='adcdecdba' *your code =7 * ans=-1

              • + 0 comments

                Yes..you are right.. Thank you very much..

              • + 1 comment

                How is it ensured that the string is palindrome just by checking if first and last are same and second and second last are same ?, i mean we have to check the whole string. I am talking about the "if and else if condition".

              • + 0 comments

                I think the same, u just check the next char too in both cases and it passes all cases..... Cheers

            • + 0 comments

              That was a good example that threw the wrench in my program. If I hadn't seen the example, I could have not figured it out where am I going wrong... The guy who added this special case is really good.

        • + 1 comment

          Simple approach

          int palindromeIndex(string s) {
              int n=s.length(),x,y;
              for(int i=0,j=n-1;i<j;i++,j--){
                  if(s[i]!=s[j]){
                      string s1=s;
                      s1.erase(s1.begin()+i);
                      for(x=0,y=n-2;x<y;x++,y--){
                       if(s1[x]!=s1[y])
                           break;             
                      }
                      if(x>=y)        
                      return i;            
                      string s2=s;
                      s2.erase(s2.begin()+j);
                      for(x=0,y=n-2;x<y;x++,y--){
                       if(s2[x]!=s2[y])
                           break;                
                      }         
                      if(x>=y)        
                      return j;
                      else
                      return -1;
                  }
              }
              return -1;    
          }
          
          • + 0 comments

            Thank you for this.

      • + 3 comments

        Case number 11 14 are also correct check my py code

        n=int(raw_input())
        for n0 in range(n):
            s=list(raw_input())
            if list(reversed(s))==s:
                print -1
            else:
                for _ in range(1,(len(s)/2)+1):
                    if s[_-1]!= s[-_]:
                        break
                s1=s[:]
                del s[_-1]
                del s1[-_]
                if list(reversed(s))==s:
                    print _-1
                else:
                    print len(s)+1-_
        
        • + 1 comment

          The code is not correct, even though it has passed all given test cases it is wrong.

          EG: aabbtkbbaac your code gives output 10 but infact the answer is "-1"

          • + 1 comment

            Dude,the question said that it is ensured that the removal of a character will make the string palindrome.

            • + 1 comment

              even after removing the 10th character the resulted string is still not palindrome.

              original : aabbtkbbaac after deleting 10th character : new : aabbktbbaa

              tk and kt are different.

        • + 0 comments

          Thats really nice approach to solve this. I was removing every alphabet and checking for palindrome Which resulted in time complexity

        • + 1 comment

          Hi just wondering where this raw_input() was defined?

          • + 0 comments

            raw_input was a python 2 function superseded by just input in python 3.

      • + 0 comments

        complete solution https://www.hackerrank.com/challenges/palindrome-index/forum/comments/474736

      • + 0 comments

        Simple approach

        int palindromeIndex(string s) {
            int n=s.length(),x,y;
            for(int i=0,j=n-1;i<j;i++,j--){
                if(s[i]!=s[j]){
                    string s1=s;
                    s1.erase(s1.begin()+i);
                    for(x=0,y=n-2;x<y;x++,y--){
                     if(s1[x]!=s1[y])
                         break;             
                    }
                    if(x>=y)        
                    return i;            
                    string s2=s;
                    s2.erase(s2.begin()+j);
                    for(x=0,y=n-2;x<y;x++,y--){
                     if(s2[x]!=s2[y])
                         break;                
                    }         
                    if(x>=y)        
                    return j;
                    else
                    return -1;
                }
            }
            return -1;    
        }
        
    • + 6 comments

      Original string:
      hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh

      After deleting 8'th character:
      hgygsvlfwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh

      Please check if it is a palindrome :)

      • + 1 comment

        it is not palindrome because check after f from front and back

        • + 10 comments

          C solution:

          int main() {
          
          int t;
          scanf("%d", &t);
          while (t--) {
              char s[100005];
              scanf("%s", s);
              int l = 0;
              int r = strlen(s) - 1;
          
              while (l < r) {
                  if (s[l] == s[r]) {
                      l++;
                      r--;
                  }
                  else {
                      break;
                  }
              }
          
              if (l >= r) {
                  printf("-1\n");
                  continue;
              }
          
              int saveLeft = l;
              int saveRight = r;
          
              l++;
              int leftFault = 1;
              while (l < r) {
                  if (s[l] == s[r]) {
                      l++;
                      r--;
                  }
                  else {
                      leftFault = 0;
                      break;
                  }
              }
          
              printf("%d\n", leftFault ? saveLeft : saveRight);
          
          }
          return 0;
          

          }

          • + 1 comment

            @etayluz. I didn't get why you've used the second while loop. Can you please explain?

            • + 2 comments
              [deleted]
              • + 0 comments

                Thanks a lot.

                :)

              • + 0 comments

                It turns out that you still have to check the remaining string for symmetry. Optimizing to a single- or double-character look ahead turns out to break the solution. A good bit trickier than the grading would lead you to believe. It surely helps to make up your own test data to check for corner cases.

          • + 0 comments

            will it work for the string abc???

          • + 0 comments

            how to write code in comment

          • + 2 comments

            how to write code in comment

            • + 0 comments

              look for when commenting in the box. :|

            • + 0 comments

              copy - paste

          • + 1 comment

            how to write code in comment

            • + 0 comments

              enclose it within 3 grave accent(') three at beginning and three at last It is the key to the left of "1"

          • + 1 comment

            This solution is wrong.It doesnt take into account the cases in which either deletion on left or on right doesnt make it a palindrome.

            • + 1 comment

              That's a good point. The second while-loop runs only if the first encountered left-right character pair aren't the same. It implicitly assumes that if removing the left character doesn't make a palindrome, then removing the right character must make it a palindrome.

              In 'bugdeb', for instance, you break out of the first while loop with L=u, R=e. L gets incremented and points to g. The second while loop then compares g-e, sets 'Leftfault' to 0 and the print statement will trigger. The print statement says that removing the 'e' will make 'bugdeb' a palindrome, which is clearly not true.

              • + 0 comments

                The problem asks us to remove a 'single' character after which the string will be a plaindrome. The string 'bugdeb' cannot be considered as a test case because removal of any (1) character will not make it a plaindrome.

          • + 0 comments

            Is enought whit check the next char, I mean, if delete the i (index left to right) verify i+1 == j and i+2 == j-1, in case of delete j (index right to left) verify i == j-1 and i+1 == j-2. Is't required verify whit a 2nd loop.

            (Sorry for my english)

          • + 0 comments

            I dont understant your code can you please explain me

          • + 0 comments

            Thanks Man,

            Your code clears the concept easily.

          • + 0 comments

            Amazing code

      • + 3 comments

        @abhiranjan Please look into test cases 11, 14. These are not accepting all possible answers.

        • + 1 comment

          Yeah, i have the same issue. It seems that test cases #11 and #14 do not correspond to problem statement. Or something is missed in problem statement.

          • + 2 comments

            Nope they are good. Please check your output.

            You can download input from the submission page. Try your output after hardcoding it there.

            • + 1 comment

              Yeah, you are right! My bad.. (x__x) -> found a bug (now all 14 tests pass). Thanks for good challenge and for quick answer! ;-)

              • + 1 comment

                @garek, any hint possible(that will not spoil the challenge for me)?

                • + 0 comments

                  In my case, i did not consider all possible cases while choosing which index to remove.

                  The abhiranjan`s comment with 'hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh' input was very helpful.

                  Hope, no spoiler here.

            • + 1 comment

              Try this code u will get the answer

              int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */
              char a[100007]; int size; cin>>size;

              while(size)
                  {
                  cin>>a;
              
                  int l=strlen(a);
                  int i=0,j=l-1;
                  if(l%2==0)
                      {
              
                      for(i=0;i<j;i++)
                          {
                          if(a[i]==a[j])
                              {
                              j--;
                              if(i==j)
                                  {
                                  cout<<"-1";
                                  break;
                              }
              
                              }
                          else if(a[i+1]==a[j])
                              {
                                 cout<<i;
                                 break;
                          }
                          else
                              {
                              cout<<j;
                              break;
                          }
                      }
              
                  }
                  else
                      {
                      for(i=0;i<=j;i++)
                          {
                          if(a[i]==a[j])
                              {
              
                              j--;
                               if(i==j)
                                   {
                                   cout<<"-1";
                                  break;
                               }
                              }
                          else if(a[i+1]==a[j]&& a[j-1]==a[i])
                              {
                                 if(a[i+2]==a[j-1])
                                 {   
                                 cout<<i;
                                 break;
                                 }
                                  else
                                      {
                                      cout<<j;
                                      break;
                                  }
              
                          }
              
                          else if(a[i+1]==a[j])
                              {
                                 cout<<i;
                                 break;
                          }
                          else
                              {
                              cout<<j;
                              break;
                          }
              
                          if(i+1==j)
                          {
                          cout<<"-1";
                          break;
              
                      }
              
                      }
              }
                  cout<<"\n";
              

              size--; } getch(); return 0; }

              • + 1 comment

                No need to add so many conditions. Only look at two char ahead. It will be reduces to two if conditions with two statements in each.

                • + 1 comment

                  This will pass the testcases given, but is not a correct solution to the problem. For example, deleting index 0 of "bababcbcbababa" will not solve it, but it will pass your two-pass lookahead test ("ab" = "ba"), and even a three-pass lookahead ("aba" = "aba"). You must fully check that the string sans the character you deleted is a palindrome. Our saving grace is that the answer must be one of the two indexes involved in the mismatch we found, so if our initial guess is wrong then there's only one other possibility.

                  • + 1 comment

                    There's a note in the problem description, which states that the input string will be solvable or it will be a palindrome by default. Your string isn't correct by this definition.

                    • + 1 comment

                      It's solved by deleting the character at the final index, creating the string "bababcbcbabab".

                      • + 0 comments

                        Oh, yeah, now I can see that. Sorry)

        • + 0 comments

          in 11th test case after deleting the 8th letter in the word it still doesnt make a pallindrome :P

        • + 1 comment
          [deleted]
          • + 0 comments

            Here is my c++ solution : explanation here https://youtu.be/QjHpvMdfnqs,

             bool isPalindrome(string s){
                 string r = s;
                 reverse(r.begin(), r.end());
                 return s == r;
             }
            
            int palindromeIndex(string input) {
                int s, e;
                for(s = 0, e = input.size() - 1; s < e; s++, e--){
                    if(input[s] != input[e]) break;
                }
                if(s >= e) return -1;
                string s1 = input, s2 = input;
                s1.erase(s1.begin() + s);
                if(isPalindrome(s1)) return s;
                s2.erase(s2.begin() + e);
                if(isPalindrome(s2)) return e;
                return -1;
            }
            
      • + 1 comment

        Thank you for this hint! it really helped me in figuring out the bug with problems 11 & 14 :) BTW, thsi problem looked easy at a first glance ... but it was kind of tricky after all!

        • + 1 comment

          what was the bug u found there?

          • + 0 comments

            Here is my c++ solution : explanation here https://youtu.be/QjHpvMdfnqs,

             bool isPalindrome(string s){
                 string r = s;
                 reverse(r.begin(), r.end());
                 return s == r;
             }
            
            int palindromeIndex(string input) {
                int s, e;
                for(s = 0, e = input.size() - 1; s < e; s++, e--){
                    if(input[s] != input[e]) break;
                }
                if(s >= e) return -1;
                string s1 = input, s2 = input;
                s1.erase(s1.begin() + s);
                if(isPalindrome(s1)) return s;
                s2.erase(s2.begin() + e);
                if(isPalindrome(s2)) return e;
                return -1;
            }
            
      • + 0 comments

        Helpful !!

      • + 0 comments

        Thank you. Your comment prompted me to rewrite my solution as a recursive function - the problem turns out to be much easier to solve this way.

      • + 0 comments

        you gotta delete the 8th char from the end. the 'w'. hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwc(w)flvsgygh

    • + 1 comment

      Same here failing on my submission; https://www.hackerrank.com/challenges/palindrome-index/submissions/code/12772467

      • + 0 comments

        You should check all symbols of a palindrome when you find the index of palindrome breaker.

    • + 0 comments

      same problem here

    • + 0 comments

      8 cannot be the ans..as string will still not be pallindrome after removing 'c'. correct ans is associated with the removal of 'w'.

    • + 0 comments

      is it working now ? m facing the same problem !

    • + 0 comments

      actually, both answers aren't correct... removing 8 "c", doesn't make the resulting string a palindrome.

    • + 1 comment

      what to print if the given string can not be converrted to palindrome????????

      • + 0 comments

        it mentioned in the question there is always a possible answere, but in case you want to do it your satisfaction , you can try some if-else condition and print some message. but will not be related to problem

    • + 2 comments

      Actually the test case #11 and #14 should be fine. If you change the order of check logic, you may fail another 2 test cases. I think the problem lies on "checking s[j+1] & s[k], s[j]&s[k-1] is not sufficient". Try checking s[j+2] & s[k-1] also. I'm able to pass all test cases :)

      Try these 3 test cases:

      abcba

      cwwcw

      wcwwc

      • + 0 comments

        int main() { int t; cin>>t; for(int i=0;i>str; long long int m; long long int k=strlen(str);

            int flag=0;
            long long int l,j;
            for(l=0;l<k/2;l++){
               // j=k-1-l;
                j=k-l-1;
                if(str[l]!=str[j]){
                    flag=1;
                    break;
                }
            }
            if(flag==1){
                if(str[l]!=str[l+1])
                    m=l;
                else if(str[j]!=str[j+1])
                    m=j;
            }
            if(flag==0){
                m=-1;
            }
            cout<<m<<"\n";
        }
        
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
        return 0;
        

        }

        successfully passed 1st 10 test cases.not able to pass remaining 4 plzzz help

      • + 0 comments

        even checking j+2 & k-1 won't suffice (even if you pass all the testcases). try with this case: abaabab.

        the solution should be, try to remove s(i) and check if it becomes a palindrome.

    • + 0 comments

      44 is the only correct answer. If you remove char 8, the resultant string is not palindromic. You're only checking one character deep after finding the end of the initial palindrome.

    • + 0 comments

      Thought I was going crazy...

    • + 1 comment

      You need to look one character beyond that. On the right side (going from right to left), the characters are wcwns.... On the left side (going from left to right), the characters are cwns.... You have to remove only w, because removing c will not result in a palindrome.

      • + 1 comment

        thanx just added && (s.charAt(start+2) == s.charAt(end-1)) then all test cases passed

        public class Solution {
            static int palindromeIndex(String s){
                int len =  s.length();
                int start = 0, end = len-1;      
                while(start<end){
                    if(s.charAt(start)!=s.charAt(end)){
                        if((s.charAt(start+1)==s.charAt(end)) && (s.charAt(start+2) == s.charAt(end-1)))
                            return start;
                        else
                            return end;
                    }
                    start++;
                    end--;
                }
                return -1;
            }
        
        • + 0 comments

          for string - "abcdefghzxqwgnbam", your code is returning 16, but it can never become a pelindrom and hence should return -1.

    • + 0 comments

      I guess I know why. Your algorithm is probably deleting the C(index 8) instead of w (index 44)

      Compare the original string with its reversed form: ori: hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh rev: hgygsvlfwcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcflvsgygh

      the difference appears at index 8. but the correct action is to remove index 44. If you remove 8 you wont have a palindrome.

    • + 0 comments

      Same. Issue. 11 & 14 not working

    • + 0 comments
      Remove i=8 
      Outside:    hgygsvlfc       cflvsgygh
      Middle:     wnswtuhmyaljkqlqjjqlqkjlaymhutwsnw
      
      Remove i=44
      Outside:    hgygsvlfw       wflvsgygh
      Inside:     cwnswtuhmyaljkqlqjjqlqkjlaymhutwsn
      

      As you can see you also need to check the next two characters to see if the string will continue to be a palindrome

      if removing i8, check first that i9 == i44 && i10 == i43
      
      
      if removing i44, check first that i8 == i43 && i9 == i42
      
    • + 0 comments

      All test cases are correct, these are just tricky.

    • + 3 comments

      check this in java import java.io.; import java.util.;

      public class Solution {

      public static boolean palindrome(String s){
          StringBuffer sb = new StringBuffer();
              sb = sb.append(s);
              sb = sb.reverse();
              String n = sb.toString();
             if(n.equals(s)){
                 return true;
             }
          else return false;
      }
      public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int n = sc.nextInt();
          for(int a=0; a<n; a++){
              int out = 0;
              String input = sc.next();           
              if(palindrome(input)){
                  System.out.println("-1");
              }
              else{
                  for(int i=0; i<input.length(); i++){
                      StringBuilder ss = new StringBuilder(input);
                      if(input.charAt(i)!=input.charAt(input.length()-i-1)){
                       if(palindrome(ss.deleteCharAt(i).toString())){
                           System.out.println(i);
                       }
                          else System.out.println(input.length()-i-1);
                               break;
                      }
                  }
              }
          }
      }
      

      }

      • + 0 comments

        what about the case "abc"?

      • + 0 comments

        Please test your code with the follwoing test case : bugdeb Your code returns an index 4. but once we remove 'e', it is still not a palindrome. You should fix that.

      • + 0 comments

        I got mistake in my code from your code.Thanks

    • + 1 comment

      It is the same even after two years, it is not accepting either one of both the valid answers

      • + 0 comments

        the s.charAt() function accepts only int values in the brackets...so mayb if the length of the string is more than the int range, which is the case in 11 and 14..and hence mayb showing wrong answer

    • + 0 comments

      include

      include

      include

      include

      include

      using namespace std;

      int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */
      int t; cin>>t; while(t--) { string s; cin>>s; int i,j; i=0; j=s.length()-1; int flag=0; int ind=0; int d=0; while(i

                  if(s[i+1]==s[j]&&s[i]==s[j-1]){
      
                      if(s[i+1]==s[j-2])
                          {
                         ind=j;
                          j--;
      
                      }
                      else if(s[j-1]==s[i+2])
                          {
                          ind=i;
                          i++;
                      }
      
                  else{
                      flag=1;
                      break;
                  }                    
                  }
                  else if(s[i+1]==s[j])
                      {
                      ind=i;
                      d=1;
                      j++;
                  }
                  else if(s[i]==s[j-1])
                      {
                      ind =j;
                      d=1;
                      i--;
                  }
                  else{
                      flag=1;
                      break;
                  }
              }
              i++;
              j--;
          }
          if(flag==1)
              {
              cout<<"-1"<<endl;
              continue;
          }
          else{
              if(d==0&&ind==0)
                  {
                  cout<<"-1"<<endl;
              }
              else{
                  cout<<ind<<endl;}
          }
      }
      return 0;
      

      }

    • + 1 comment

      The program is correct check my py code

      n=int(raw_input())
      for n0 in range(n):
          s=list(raw_input())
          if list(reversed(s))==s:
              print -1
          else:
              for _ in range(1,(len(s)/2)+1):
                  if s[_-1]!= s[-_]:
                      break
              s1=s[:]
              del s[_-1]
              del s1[-_]
              if list(reversed(s))==s:
                  print _-1
              else:
                  print len(s)+1-_
      
      • + 0 comments

        why would you use an underscore if you're actually accessing the value.... very anti-pythonic

    • + 0 comments
      int q;
      cin >> q;
      for(int a0 = 0; a0 < q; a0++){
          string s;
          cin >> s;
      
          int i;
          for (i=0;i<s.length()/2;i++) {
              if (s[i]==s[s.length()-1-i]) continue;
      
              // check if substr is palindrome by getting rid of ith char
              int j;
              for (j=i+1;j<i+1+(s.length()-1-i-i)/2;j++) {               
                  if (s[j]==s[s.length()-j]) continue;
                  cout << s.length()-1-i << endl;
                  break;
              }
              if (j==i+1+(s.length()-1-i-i)/2) cout << i << endl;
              break;
          }
          if (i==s.length()/2) cout << -1 << endl;
      }
      
    • + 0 comments

      only w can be removed at 44th index

    • [deleted]
      + 2 comments
      public static void main(String[] args) {
      
              try (Scanner scanner = new Scanner(System.in)) {
                  int numberOfTestCases = scanner.nextInt();
                  for (int i = 0; i < numberOfTestCases; i++) {
                      String next = scanner.next();
                      int indexOfChange = makePalindrome(next);
                      System.out.println(indexOfChange);
                  }
              }
          }
      
          private static int makePalindrome(String text) {
      
              int removedIndex = -1;
      
              boolean palindrone = isPalindrone(text);
              if (palindrone) {
                  removedIndex = -1;
              } else {
                  StringBuilder builder;
                  int left = 0;
                  int right = text.length() - 1;
                  boolean found = false;
                  while (left < right && !found) {
                      if (text.charAt(left) != text.charAt(right)) {
                          builder = new StringBuilder(text);
                          builder.delete(left, left + 1);
                          if (isPalindrone(builder.toString())) {
                              removedIndex = left;
                          } else {
                              removedIndex = right;
                          }
                          found = true;
                      }
                      left++;
                      right--;
                  }
              }
      
              return removedIndex;
          }
      
          private static boolean isPalindrone(String text) {
      
              int left = 0;
              int right = text.length() - 1;
      
              while (left < right) {
                  if (text.charAt(left) != text.charAt(right)) {
                      return false;
                  }
                  left++;
                  right--;
              }
      
              return true;
          }
      
      • + 0 comments

        The above algo is wrong, if you input "avidefdxiva" it gives output as 7, but it should be -1 as by removing 7th index the resultant string ("avidefdiva") won't be a palindrome.

      • + 0 comments

        And why is builder = new StringBuilder(text); done each time. just restore the deleted char. If we create a new object then it is no better than using String itself.

    • + 3 comments

      TC11 and 14 are correct... here is my solution

      static int palindromeIndex(String s) {
              for(int i = 0, j = s.length() - 1; i < j; i++, j--) {
                  if(s.charAt(i) != s.charAt(j)) {
                      if(s.charAt(i+1) != s.charAt(j))
                          return j;
                      else if(s.charAt(i) != s.charAt(j-1)) 
                          return i;
                      else {
                          if(s.charAt(i+2) != s.charAt(j-1))
                              return j;
                          if(s.charAt(i+1) != s.charAt(j-2))
                              return i;
                      }
                  }
              }
              return -1;
          }
      
      • + 0 comments

        Have a similar code, but missed the login in 'else' stametent. You have great solution!

      • + 0 comments

        The above algo is wrong, if you input "avixdefdiva" it gives output as 3, but it should be -1 as by removing 3rd index the resultant string ("avidefdiva") won't be a palindrome.

      • + 0 comments

        For string - "abcdefghzxqwgnbam", your code is returning 16, but it can never become a pelindrom and hence should return -1.

    • + 0 comments

      My simple solution is like this :

      static int palindromeIndex(String s){
              // Complete this function
              int i, res = -1, n, temp;
              char[] charStr = s.toCharArray();
              
              n = s.length();
              
              for( i= 0; i< n; i++) {
                  temp = charStr[i] - charStr[n-1 -i];
                  if(temp == 0)
                      continue;
                  else
                      if((charStr[i+1] - charStr[n-1 -i] == 0) && (charStr[i+2] == charStr[n-2 -i])){
                          res = i;
                          break;
                      }
                      else{
                          res = n-1 -i;
                          break;
                      }
                      
              }
              return res;
              
          }
      
    • + 0 comments

      Rather than checking for only the next character after a mismatch,check for the next two characters.

    • + 0 comments

      Yea these cases are bit tricky ones you need to backtrack to the postion you have earlier selected n choose different path(i.e if you choose 8 for deletion now select len-8) when characters are not matching.

    • + 0 comments

      The string: "hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh" is present in testcase #11, and also in testcase #1. In #1, if the code returns 8, it's fine, but en #11, return of an 8 fails the test

    • + 0 comments

      complete solution https://www.hackerrank.com/challenges/palindrome-index/forum/comments/474736

    • + 1 comment

      I made another approach for this problem in Python 3: * invert all the string and store in s_i * Iterarate s removing postion from start to end and iterate s_i removing postion from end to start * if s and s_i are equals, return postion

      This solution pass in all test cases.

      def palindromeIndex(s):
              N = len(s)
              N_i = N - 1
              s_i = s[::-1]
              if s == s_i:
                      return -1
      
              for i in range(N):
                      test = s[:i] + s[i+1:]
                      test_i = s_i[:N_i-i] + s_i[N_i-i+1:]
                      if test == test_i:
                              return i
      
              return -1
      
      • + 0 comments

        no response on stdout

    • + 1 comment

      I think this would help

      def palindromeIndex(s):
          n = len(s)
          for i in range(n//2):
              if s[i]!= s[n-i-1]:
                  if s[i]==s[n-i-2] and s[i+1]==s[n-i-3]:
                      return n-i-1
                  else:
                      return i
          return -1
      
      • + 0 comments

        You need another test before you return i. For example, this fails if s="abcdefxdcbaa"

    • + 0 comments

      My code in C++:

      include

      include

      using namespace std;

      int main(){

      int q,i,j,count,pos1,pos2,len,flag,flag1; string str;

      cin>>q;

      for(int k=0;k

      flag=0,flag1=0; cin>>str;

      len =str.length();

      for(i=0,j=len-1;i

      if(str[i]!=str[j]){ pos1=i; pos2=j; flag=1; break; } }

      if(flag==0){ cout<<"-1\n"; continue; }

      str.erase(str.begin() + pos1);

      int len1=str.length(); for(i=0;i < len1/2 ;i++){ if(str[i] != str[len1-i-1]){ flag1 = 1; break; } }

      if (flag1) { cout< else { cout<

      } return 0; }

    • + 0 comments

      You are right . same problem

    • + 0 comments

      I was getting th same issue and I adjusted my code to suit the outputs. Here's my JS solution:

          if(s.split(``).reverse().join(``) !== s){
              let half = Math.floor(s.length * 0.5);
      
              for(let i = 0; i < half; i++){
                  let id = s.length - 1 - i;
                  if(s.charAt(i) !== s.charAt(id)){
                      let sub = s.substring(i,id);
                      if(sub === sub.split(``).reverse().join(``)){
                          return id;
                      }
                      sub = s.substring(i+1,id+1);
                      
                      if(sub === sub.split(``).reverse().join(``)){
                          return i;
                      }
                      else{
                          break;
                      }
                  }
              }
          }
          return -1;
      
    • + 0 comments

      6 years have elapsed since you posted this error and it still remains there. Testcase 11 and 14 fails.

    • + 0 comments

      We also need to check whether the subsequent elements are palindrome, as only one removal is needed we just check for the next elements to be equal.

      int palindromeIndex(string s) {

      for(int i=0;i<s.size()/2;i++){
          if(s[i]!=s[s.size()-1-i]){
              if(s[i]==s[s.size()-2-i] && s[i+1]==s[s.size()-3-i])
                  return s.size()-1-i;
              else
                  return i;
          }
      }
      return -1;
      

      }

    • + 0 comments

      same happening wih me.

    • + 1 comment

      My code result in TLE only for TC2 & TC5

      Can Some optimze it using similar approach


          static int palindromeIndex(String s)
          {
              boolean once;
              int j, k, len = s.length();
      
              for(j = 0 , k = len - 1 ; j < k ; j++, k--)
                  if(!(s.charAt(j) == s.charAt(k)))
                      break;
              if(j >= k)
                  return -1;
      
              for(int i = 0; i < len ; i++)
              {
                  j = 0;
                  k = len - 1;
                  once = true;
                  while(j < k)
                  {
                      if(i == j && once)
                      {
                          j++;
                          once = false;
                          continue;
                      }
                      else if(i == k && once)
                      {
                          k--;
                          once = false;
                          continue;
                      }
                      if(s.charAt(j) == s.charAt(k))
                      {
                          j++;
                          k--;
                      }
                      else
                          break;
                  }
                  if(j >= k) return i;
              }
              return -1;
          }
      

      Edit: New Solution

          static int palindromeIndex(String s)
          {
              int i, j, x, y, len = s.length();
      
              for(i = 0 , j = len - 1 ; i < j ; i++, j--)
                  if(!(s.charAt(i) == s.charAt(j)))
                      break;
              if(i >= j)
                  return -1;
      
              for(x = i + 1, y = j ; x < y ; x++, y--)
                  if(!(s.charAt(x) == s.charAt(y)))
                      break;
              
              if(x >= y)
                  return i;
              else
                  return j;
          }
      
      • + 1 comment

        How about this?

        static int palindromeIndex(String s)
            {
                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;
            }
        
        • + 1 comment
          [deleted]
          • + 0 comments

            okay....thnks @vishalbty, i don't y it initially looked me so complex :)

    • + 0 comments

      This question is little bit weird . You have to assume that a given string is a pallindrome or just off by a single character . So basically you have to run a loop from both starting and ending and check which characters dont match. Now you have to remove any one of the character and check if the string is pallindrome .If yes return the index of the character removed or else return the index of other character (the character which didnt match at the start) .Just look at this code and you will understand what i was taking about .(Its a java code btw )

                  int low = 0 ; 
          int high = s.length()-1 ;
          while(low < high)
          {
              if(s.charAt(low) != s.charAt(high))
              {
                  break;
              }
              low++;
              high--;
      
          }
          if(low > high)
          {
              return -1; 
          }
      
          int res1 = high ;
          int res2 = low ;
         while(low < high)
         {
             if(s.charAt(low+1) != s.charAt(high))
             {
                 return res1 ;
             }
             low++;
             high--;
         }
         return res2 ;
      
    • + 0 comments

      The problem of test case 11 and 14 is that you have to check two index ahead in both cases hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh mismatch at index 8 so if you remove c at index 8 just checking after c is w then it will fail cause it won't be palindrome.

    • + 0 comments

      Check you answer for sample case: cwccw You'll get an better understanding. You can check my code, it works....

      ` python3 code

      def palindromeIndex(s):
      
              n = len(s)
      
              if ispalindrome(s):
                      return -1 
      
              k = 0
              for i in range(n//2):
                      if s[-i-1]!=s[i]:
                              if s[-i-2]==s[i] or s[i+1]==s[-i-1]:
                                      wrd = remove(s,n-i-1)
                                      if ispalindrome(wrd):
                                              return n-i-1 
      
                                      wrd = remove(s,i)
                                      if ispalindrome(wrd):
                                              return i
      
              return -1
      >             
      
    • + 0 comments

      NO BRO...your string is "hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh"

      If you remove all middle equal characters it will be

      "hgygsvlfcw - nswtuhmyaljkqlqjjqlqkjlaymhutwsn - wcwflvsgygh"

      here you find one 'w' is extra...

      "hgygsvlfcwwcwflvsgygh"

    • + 0 comments

      brother, if we remove 8th letter 'c' we get .....fwns...... front left and from right we get ......fwcwns.... . but if we remove 44 letter we get a palandrome. i faced the same problem , so i sort to check the third letter after mismatch

      if s[i]!=s[j]: if s[i]==s[j-1] and s[i+1]==s[j-2]: return j else return i

    • + 0 comments

      I had the same problem but I solved the problem with the string you shared. Thank you. My solution is:

      for (int i = 0, j = s.Length - 1; i < s.Length / 2 && j >= s.Length / 2; i++, j--) { if (s[i] != s[j]) { if(s[i] == s[j - 1] && s[i + 1] == s[j]) { if (s[i + 1] == s[j - 2]) index = j; else index = i; } else if (s[i + 1] == s[j]) index = i; else if (s[i] == s[j - 1]) index = j; break; } } return index;

    • + 0 comments

      Testcase 11 and 14 are CORRECT.

      correct explanation to soln is explained by this thread. https://www.hackerrank.com/challenges/palindrome-index/forum/comments/121372

      https://www.hackerrank.com/challenges/palindrome-index/forum/comments/60201

    • + 0 comments

      no, removing any of both char won't work, it has to be only 'w'(idx 44) because.. the string is "...fcwn...nwcwf..." (dots are all palindrome only you can check), now after char 'f', 'c'(idx 8) and 'w' char are different, now if you remove 'c' here.. the string would be "...fwn...nwcwf..." which doesn't make the string palindrome, but if you remove w, the string will be "...fcwn...nwcf..." which is palindrome, that's why here answer should be 44, not 8

    • [deleted]
      + 0 comments
      //I THINK THIS MAY BE READABLE (C++)
          bool palindrome(string s)
       {
       int l=s.size();
       for(int i=0;i<l/2;i++)
        {
         if(s[i]!=s[l-i-1])
         return false;
        }  
       return true;
      }
       int palindromeIndex(string s) {
      int x,y;
       int l=s.size();
      for(int i=0;i<l/2;i++)
        {
      if(s[i]!=s[l-i-1])
      {
          x=i;
          y=l-i-1;
          break;
      }
        }
      s=s.substr(0,x)+s.substr(x+1,s.size());
      if(palindrome(s))
       {
       return x;
       }
       else {
       return y;
       }
        }
      
    • + 0 comments

      My first algorithm was also failing tests 11 and 14. But I realized it was a problem of the algorithm, not of the test. If you remove 8th caracter from the string "hgygsvlfcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcwflvsgygh" it will not become a palindrome. I have 'isolated' my algorithm problem here.

      "cwnnwcw"

      We have to remove 6th carachter to form a palindrome.

    • + 0 comments

      For anoyone still looking for an O(n) solution (2 pointers) that passes test cases 11 and 14, here's a working C# solution with comments:

      the issue with 11 & 14 is that we could remove/skip either the left or right character when iterating through, but only 1 of them leads to a solution, so we have to check the next character as well to see if left or right is the right to remove/skip

      public static int palindromeIndex(string s)
      {
        int charRemoved = -1;
        int left=0;
        int right=s.Length-1;
        
        while (right > left) {
          if (s[left] != s[right]) {
            if (charRemoved != -1) //already removed a char, we're done
              return -1;
            
            bool removeLeft = left < s.Length -1 && s[left+1] == s[right];
            bool removeRight = right > 0 && s[left] == s[right-1];
            
            if (removeLeft && removeRight) { //if we could remove either
              //check one more char furhter in...
              removeLeft = (left+1) < s.Length-1 && s[left+2] == s[right-1]; 
              removeRight = !removeLeft;
            }
      
            if (removeLeft) {
              charRemoved = left;
              left++; //skip this character
            } else if (removeRight) {
              charRemoved = right;
              right--; //skip this character
            } else { //if removing neither character works
              return -1;
            }
          }
          //move both pointers to the next character toward the middle
          right--;
          left++;
        }
        
        return charRemoved; //return the index of the char we removed
      }
      
    • + 0 comments

      The answer is 44. I created an extra check palindrome function, and removing index 8 only does not result in a palindrome. only by removing index 44, will the resulting string be a palindrome.