I just completed the first problem in the final section of the JavaScript course, and while I’m happy that I’ve become able to write things like this, I can’t help but feel that my current code isn’t as efficient as it could be. I mostly just want to see if anyone has any recommendations on how to make the following code smaller and more efficient, as a learning opportunity for me.
Thank you in advance!
function palindrome(str) {
let arr1 = str.toLowerCase().replace(/[\W_]/g, "").split("");
let arr2 = arr1.splice(Math.floor(arr1.length / 2)).reverse();
if (arr1.length !== arr2.length) {
arr2.pop();
}
console.log(arr1, arr2);
return arr1.every(target => target === arr2[arr1.indexOf(target)]);
}
palindrome("_eye")
palindrome("0_0 (: /-\ :) 0-0");
If you want to rewrite this to be more concise I would suggest that you don’t think of the strings as an array of characters that need to be compared by index but rather as just two strings that can be compared using the === operator.
If you look for efficiency you should avoid creating additional arrays.
My take would be to just take the input, clean it up and the compare character by character:
function palindrome(str) {
const _clean = str.toLowerCase().replace(/[\W_]/g, '')
let start = 0;
let end = _clean.length - 1;
while (start < end) {
if (_clean[start++] !== _clean[end--]) {
return false
}
}
return true;
}
Thank you very much! One of the problems I ran into while writing the code I made is that it couldn’t handle the unique character in the center of the palindrome caused by an odd number of characters. The original code I wrote was something like this, but with the aforementioned excess of arrays. I take it this version isn’t confused by that extra character?
Actually, reverse() only works on Arrays, so you are doing that part correctly. After you reverse the array you can easily put it back together as a string with join().
As @jenovs suggested, you don’t really need any additional step to check if a cleaned string is palindrome, all you can do is just loop till half the string, and compare head and tail.
As soon as one of those letter differs, means that’s not a palindrome.
It has an execution time of O(n/2) (half the length of the string)