Help Me Make My Code More Efficient (Palindrome Checker)

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) {
console.log(arr1, arr2);
return arr1.every(target => target === arr2[arr1.indexOf(target)]);

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.

1 Like

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;
1 Like

That’s a very solid point, thank you very much!

I assume reverse() works on strings as well as arrays?
If not, is there a different way to handle it?

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().

1 Like

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) :slight_smile:

1 Like

If there is an odd character count start and end will be equal, that will break the while loop.

1 Like

Thank you all very much for the help!

I think I have a better idea of how to cut out unnecessary steps from my code.

I’ll keep this in mind as I continue to complete the problems in this test section.