Created
September 8, 2023 14:55
-
-
Save Shaddyjr/c6ffb89d0175a4d441b2a56da0a5e441 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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