Exploring Valid Palindromes with JavaScript

Akhil Kumar
TheCodingWay
Published in
2 min readOct 14, 2023

Valid Palindrome II Leetcode 680

AI Generated Image”Coding Palindromes”

Palindromes are fascinating sequences that read the same backward as forward. In the realm of programming, determining whether a given string can be turned into a palindrome with a single character removal is a common problem. In this article, we’ll delve into a JavaScript function, validPalindrome, that efficiently tackles this challenge.

function validPalindrome(s) {
function isPalindromeRange(i, j) {
while (i < j) {
if (s[i] !== s[j]) {
return false;
}
i++;
j--;
}
return true;
}

for (let i = 0, j = s.length - 1; i < j; i++, j--) {
if (s[i] !== s[j]) {
return isPalindromeRange(i + 1, j) || isPalindromeRange(i, j - 1);
}
}
return true;
}

Breaking Down the Code

Let’s dissect the validPalindrome function to understand how it operates:

  1. isPalindromeRange(i, j): This inner function checks if a substring within the indices i and j is a palindrome. It iterates from both ends towards the middle, comparing characters. If a mismatch is found, it returns false; otherwise, it returns true.
  2. Main Loop: The main loop runs from the start of the string (i = 0) and the end of the string (j = s.length - 1) simultaneously, converging towards the middle. At each step, it checks if the characters at the current positions are equal.
  • If they are not equal, it means a character needs to be removed. It then calls isPalindromeRange twice, once with i + 1 and j, and once with i and j - 1. This accounts for the two possible scenarios after a character is removed.
  • If the characters are equal, the loop continues.

This elegant approach allows the function to efficiently handle the task.

Using the Function

Using the validPalindrome function is straightforward. Simply pass the string you want to evaluate as an argument. The function will return true if the string can be turned into a palindrome with a single character removal, and false otherwise.

const example1 = "abca";
const example2 = "racecar";
console.log(validPalindrome(example1)); // Output: true
console.log(validPalindrome(example2)); // Output: true

Conclusion

The validPalindrome function provides an elegant solution to a common problem in programming. Its efficient approach makes it suitable for handling large strings. By leveraging techniques like this, programmers can solve a wide range of challenges with elegance and efficiency.

Remember to incorporate error handling and consider edge cases when using this function in real-world applications. Happy coding!

--

--