We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Passing all tests, in JS, in O(n) time. Not very elegant, but easy to reason about:
functionpalindromeIndex(s){letcandidatesLeft=[];letcandidatesRight=[];leti=0;letj=s.length-1;// check candidates in left indexwhile(i<=j){if(s[i]!==s[j]){if(s[i+1]===s[j]){candidatesLeft.push(i);i=i+2;j--;continue;}}i++;j--;}if(candidatesLeft.length===1){returncandidatesLeft.pop();}// check candidates in right indexi=0;j=s.length-1;while(i<=j){if(s[i]!==s[j]){if(s[i]===s[j-1]){candidatesRight.push(j);j=j-2;i++;continue;}}i++;j--;}// it's already a palindromeif(candidatesRight.length===0&&candidatesLeft.length===0){return-1;}if(candidatesRight.length===1){returncandidatesRight.pop();}return-1;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Palindrome Index
You are viewing a single comment's thread. Return to all comments →
Passing all tests, in JS, in O(n) time. Not very elegant, but easy to reason about: