Collection of array manipulation algorithms including searching, sorting, and sum-based problems.
Methods
# static isPalindrome(str) → {boolean}
Checks if a given string is a palindrome (reads the same forwards and backwards).
This implementation normalizes the input by converting to lowercase and removing non-alphanumeric characters before comparison. It uses two pointers approach for efficient checking.
Algorithm
- Clean the input string by removing non-alphanumeric characters and converting to lowercase.
- Use two pointers (start and end) to compare characters from both ends moving inward.
- If any mismatch is found, return false.
- If all characters match, return true.
Constraints
- Input string can contain letters, numbers, spaces, and special characters.
- Comparison is case-insensitive.
- Non-alphanumeric characters are ignored.
- Empty strings and single characters are considered palindromes.
Edge Cases
- Empty string returns
true. - Single character returns
true. - Strings with only spaces/special characters return
true. - Handles Unicode characters.
Complexity:
- Time: O(n) — Where n is the length of the cleaned string.
- Space: O(n) — For storing the cleaned string.
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string
|
The string to check for palindrome property. |
- Since:
- 1.0.0
- See:
-
isAnagram- For checking if two strings are anagramsreverseString- For reversing a string- Palindrome (Wikipedia)
If input is not a string.
TypeError
Returns true if the string is a palindrome, false otherwise.
boolean
Examples
Basic palindrome check
isPalindrome("racecar");
// → true
Case-insensitive check
isPalindrome("RaceCar");
// → true
Ignores spaces and punctuation
isPalindrome("A man, a plan, a canal: Panama");
// → true
Non-palindrome string
isPalindrome("hello");
// → false
Empty string is palindrome
isPalindrome("");
// → true
Single character is palindrome
isPalindrome("a");
// → true
Numbers in string
isPalindrome("12321");
// → true
Real-world usage: Form validation
const userInput = "Was it a car or a cat I saw?";
if (isPalindrome(userInput)) {
console.log("That's a palindrome!");
}