Skip to content

Instantly share code, notes, and snippets.

@cjativa
Created October 31, 2024 02:29
Show Gist options
  • Save cjativa/6c04029ee9dec86bb2cf607530b1fa09 to your computer and use it in GitHub Desktop.
Save cjativa/6c04029ee9dec86bb2cf607530b1fa09 to your computer and use it in GitHub Desktop.
function isPalindrome(input: string): boolean {
// Our approach to checking this input string for the quality of being a palindrome will be the following
// 1. A single-character string is technically a Palindrome. We'll return true immediately if this is the case
// 2. We'll split the input into an array of its characters
// 3. We'll utilize a `while` loop to check the leftmost and rightmost characters of the input string - modifying it in-place as we do so using shift and pop
// There's a base-case to handle, that once we reach a length of 1, we can consider the number a palindrome
// If at any point, our leftmost and rightmost values are not equivalent, then the input number is not a palindrome
// A single-character string is technically a Palindrome
if (input.length === 1) {
return true;
}
const inputSplit = input.toString().split('');
// Our exit- condition will be once our input split has no characters left to check
while (inputSplit.length) {
// If we've reached a length of 1 after popping and validating
// the leftmost and rightmost values, then we have a palindrome
if (inputSplit.length === 1) {
return true;
}
const leftmost = inputSplit.shift();
const rightmost = inputSplit.pop();
// The leftmost and rightmost values need to be the same for it to have been a valid palindrome
if ((leftmost === rightmost) === false) {
return false;
}
}
// Down here, we handle the case of a input string like `abba`
// Where we would have validated both the leftmost and rightmost
// values, but we end up breaking out of our while-loop due to 0 characters left
// Since we didn't encounter the failure conditions, then this had to be a palindrome
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment