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.
functionpalindromeIndex(s){// Write your code hereletleftIdx=0letrightIdx=s.length-1constresult=[]while(leftIdx<rightIdx){console.log(`leftxright(${leftIdx},${rightIdx}):`,s[leftIdx],s[rightIdx])if(s[leftIdx]===s[rightIdx]){// There's no candidate to remove in this pair, we can now// increase left index and decrease right indexleftIdx++rightIdx--continue}// There should be some candidate to remove now// If there was some candidate to remove before, we can return -1 immediatelyif(result.length===1)return-1// This is in case of 'aawcwabawcaa', where we have candidates to remove// on both sides, removing first on the side with most candidates// will give us a palindromeletleftCandidates=0letrightCandidates=0// Let's define additional index/counter not to disturb left/right indicesletcounter=0// Let's repeat that block until one of the sides has more candidates to remove// This will tell us which candidate should be really removedwhile(leftCandidates===rightCandidates){if(s[leftIdx+counter]===s[rightIdx-counter-1]){// We found a candidate to remove on the right sideconsole.log('removing',rightIdx+counter,s[rightIdx+counter])rightCandidates++}if(s[leftIdx+counter+1]===s[rightIdx-counter]){// We found a candidate to remove on the left sideconsole.log('removing',leftIdx+counter,s[leftIdx+counter])leftCandidates++}counter++}if(leftCandidates>rightCandidates){// There's more candidates on the left side, we should remove firstresult.push(leftIdx)leftIdx++}elseif(rightCandidates>leftCandidates){// There's more candidates on the right side, we should remove firstresult.push(rightIdx)rightIdx--}}console.log('result:',result[0]||-1)returnresult.length?result[0]:-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 →
Here's my solution to this problem in JS: