Write a function to reverse a string and use it to check for a palindrome.
Split the string into characters, reverse the array and join it back. A palindrome reads the same both ways, so clean the text (lowercase, letters and digits only) and compare it with its reverse.
Explain it simply
Strings have no reverse method, but arrays do. So the recipe is: string to array, reverse the array, array back to string.
A palindrome like "madam" reads the same backwards. Real inputs have spaces, commas and capital letters ("A man, a plan, a canal: Panama"), so first lowercase everything and strip anything that is not a letter or digit with a regular expression.
Another way is two pointers: compare the first and last character, move inward, and stop at the first mismatch. That avoids building a second string.
Line by line
function reverse(str) {
return str.split("").reverse().join("");
}
function isPalindrome(text) {
const clean = text.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === reverse(clean);
}
console.log(reverse("India")); // Output: aidnI
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true
console.log(isPalindrome("hello")); // Output: falseWhat to say in the interview
"I split into characters, reverse and join for the reverse. For palindromes I normalise the string first, then compare it to its reverse, or use two pointers to avoid the extra copy. split('') breaks on emoji, so for those I would use Array.from."
Complexity
Time O(n), space O(n) for the cleaned copy and the reversed copy. The two-pointer version uses O(1) extra space after cleaning.
Common mistakes
- Forgetting to remove spaces and punctuation before comparing.
- Comparing with == on arrays instead of strings.