A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, words like "madam" and "racecar" are palindromes.
Example:
Input: s = "abba"
Output: true
Explanation: s is a palindromeInput: s = "abc"
Output: false
Explanation: s is not a palindrome
1. Using for loop (Efficient Approach)
In this approach, we use a for loop to iterate through the string from both ends, comparing characters simultaneously. This method is efficient because it can stop early if any mismatched characters are found.
function isPalindrome(str) {
let j = str.length - 1
for (let i = 0; i < str.length / 2; i++) {
if (str[i] != str[j]) {
return false;
}
j--;
}
return true;
}
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));
Output
true true false
2. Checking the String from Last
This approach manually reverses the string by iterating from the end to the start, and then compares the reversed string with the original one. If both are identical, the string is a palindrome.
function isPalindrome(str) {
let rev = "";
for (let i = str.length - 1; i >= 0; i--) {
rev += str[i];
}
if (rev == str) {
return true
} else {
return false;
}
}
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));
Output
true true false
3. Using split(), reverse() and join() Methods
JavaScript provides built-in methods that can simplify the palindrome check. We can use split(), reverse(), and join() methods to reverse a string and compare it with the original string in just a few lines of code
function isPalindrome(str) {
let rev = str.split("").reverse().join("");
if (rev == str) {
return true
}
return false
}
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));
Output
true true false
Use Cases for Palindromes
Palindromes are not just for fun with words! They have practical applications in programming, such as:
- Palindrome Strings: Checking if a word or phrase is a palindrome is often part of interview questions or puzzle-solving challenges.
- Palindrome Numbers: They are sometimes used in algorithms, such as detecting symmetric numbers in certain computational problems.
- Data Validation: Some data validation tasks may involve ensuring that input values are symmetric, such as in DNA sequence matching or other symmetrical data checks.