101 Logo
onenoughtone

Code Implementation

Palindrome Checker Implementation

Below is the implementation of the palindrome checker:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Checks if a string is a palindrome (reads the same forward and backward).
* Ignores non-alphanumeric characters and is case-insensitive.
*
* @param {string} s - The input string to check
* @return {boolean} - True if the string is a palindrome, false otherwise
*/
function isPalindrome(s) {
// Initialize two pointers
let left = 0;
let right = s.length - 1;
while (left < right) {
// Skip non-alphanumeric characters from left
while (left < right && !isAlphanumeric(s[left])) {
left++;
}
// Skip non-alphanumeric characters from right
while (left < right && !isAlphanumeric(s[right])) {
right--;
}
// Compare characters (case-insensitive)
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
// Move pointers toward each other
left++;
right--;
}
// If we get here, the string is a palindrome
return true;
}
/**
* Helper function to check if a character is alphanumeric
*/
function isAlphanumeric(char) {
const code = char.charCodeAt(0);
return (
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) // a-z
);
}
// Alternative implementation using built-in methods
function isPalindromeAlt(s) {
// Clean the string: remove non-alphanumeric and convert to lowercase
const cleaned = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
// Check if the cleaned string equals its reverse
const reversed = cleaned.split('').reverse().join('');
return cleaned === reversed;
}
// Test cases
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
console.log(isPalindrome("")); // true (empty string is a palindrome)
console.log(isPalindromeAlt("racecar")); // true
console.log(isPalindromeAlt("hello")); // false
console.log(isPalindromeAlt("A man, a plan, a canal: Panama")); // true
console.log(isPalindromeAlt("")); // true

Step-by-Step Explanation

Let's break down the implementation:

  1. Initialize Pointers: Initialize two pointers at the beginning and end of the string.
  2. Skip Non-Alphanumeric: Skip non-alphanumeric characters as we move the pointers.
  3. Compare Characters: Compare characters at both pointers (case-insensitively).
  4. Check for Mismatches: If characters don't match, return false.
  5. Verify Palindrome: If pointers meet in the middle without mismatches, return true.
ProblemSolutionCode
101 Logo
onenoughtone