Coding Interview Questions | Valid Palindrome
December 15th, 2023
Introduction:
This summary will talk about my solution to the valid palindrome problem as seen on leetcode here.
Solution:
function isPalindrome(s: string): boolean {
const escapedString = s.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
// An empty string is by definition a palindrome
if (!escapedString.length) {
return true;
}
let forwardPointerIdx = 0;
let endingPointerIdx = escapedString.length - 1;
while (forwardPointerIdx < endingPointerIdx) {
const forwardCharacter = escapedString[forwardPointerIdx];
const endingCharacter = escapedString[endingPointerIdx];
if (forwardCharacter !== endingCharacter) {
return false;
}
forwardPointerIdx++;
endingPointerIdx--;
}
return true;
}
Summary:
The solution above defines a function that checks if a given string is a palindrome. In order of steps completed:
- It removes non-alphanumeric characters from the input string using a regular expression (
/[^A-Za-z0-9]/g
). - It converts the resulting string to lowercase.
- If the processed string is empty, the function returns
true
as an empty string is considered a palindrome per the problem definition. - The function uses two pointers (forward and ending) to iterate through the characters of the processed string from both ends.
- It compares the characters at the forward and ending positions. If they are not equal, the function returns
false
immediately. - If the loop completes without finding unequal characters, the function returns
true
, indicating that the string is a palindrome.