Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created September 8, 2023 14:55
Show Gist options
  • Save Shaddyjr/c6ffb89d0175a4d441b2a56da0a5e441 to your computer and use it in GitHub Desktop.
Save Shaddyjr/c6ffb89d0175a4d441b2a56da0a5e441 to your computer and use it in GitHub Desktop.
// source: https://www.hackerrank.com/challenges/palindrome-index/problem
// video: https://youtu.be/IoiYMKmvuPQ
function isPalindrome(s){
let left = 0
let right = s.length - 1
while(left < right){ // O(n)
if(s[left]!==s[right]){
return false
}
left++
right--
}
return true
}
function palindromeIndex(s) {
// Check from both ends for palindrome, allowing for 1 error
let left = 0
let right = s.length - 1
while(left < right){ // O(n)
if(s[left] !== s[right]){
// Found error!
// We just don't know which side has the error, so just check both
if(isPalindrome(s.slice(left + 1, right + 1))){
return left
}else if(isPalindrome(s.slice(left, right))){
return right
}
return -1 // There was more than one error
}
left++
right--
}
// Total Time Complexity = O(n)
return -1 // Result was a palindrome without error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment