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.
functionpalindromeIndex1(s:string):number{// function check string [s] is palidromeconstisPalindrome=(s:string):boolean=>{for(leti=0;i<Math.floor(s.length/2);i++){letri=s.length-i-1if(s[i]!=s[ri])returnfalse}returntrue}// 1. check [s] isn't palindrome alreadyif(!isPalindrome(s)){// 2. loop [s]...for(leti=0;i<s.length;i++)// 3. remove each character by [i], check remain [s] is palindromeif(isPalindrome(s.slice(0,i)+s.slice(i+1)))// 4. found palindrome, return [i]returni}// 4. [s] alreay palidome, return -1return-1;}
Second attemp is optimal
functionpalindromeIndex(s:string):number{// function check string [s] is palidromeconstisPalindrome=(start:number,end:number):boolean=>{while(start<end){if(s[start]!=s[end])returnfalse;start++;end--;}returntrue;}/** * solution 1 works fine but it seems to be suboptimal. * new idea is define 2 index at start and end of [s], reduce to middle. * only check 2 case when non palindrome found * + case1: start removed * + case2: end removed * orelse non of [s] can be palindrome, return -1 */// 1. define [start] and [end]letstart=0letend=s.length-1// 2. loop ... recude [start] and [end] to middlewhile(start<end){// 3. if [s] at [start] and [end] is not equal, mean not palidrome at [start] to [end]if(s[start]!=s[end]){// 4.1 try remove [start], check palidrome ... return if foundif(isPalindrome(start+1,end))returnstart// 4.2 try remove [end], check palidrome ... return if foundif(isPalindrome(start,end-1))returnend}start++end--}// [start] and [end] go throuth [s] but palidrome not found, return -1return-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 →
My answer with Typescript, both worked.
First attemp that simple
Second attemp is optimal