Solution Explanation please?: Check for Palindromes

Tell us what’s happening:
I saw this intermediate code solution on: freeCodeCamp Algorithm Challenge Guide: Check for Palindromes

function palindrome(str) {

  str = str.toLowerCase().replace(/[\W_]/g, '');
  for(var i = 0, len = str.length - 1; i < len/2; i++) {
    if(str[i] !== str[len-i]) {
      return false;
    }
  }
  return true;
}
palindrome("1 eye for of 1 eye.");
  • Question 1:
    Isn’t the condition expression in the For Loops, where i < len/2, skip the center-most letters during some test? for example, “almostomla”: str.length=10, ends up with i<4.5. therefore it never tests i=5 and i=6, and it would return true when the correct answer is false. Can anybody explain to me why does this solution still work? maybe it connects with my second question, but I just couldn’t make sense of it logically.

  • Question 2:
    When I tried to rewrite my own code after looking through the solution, I set return true within the if statement ( and yes I changed the if statement itself too ), and the test “1 eye for of 1 eye.” failed and gives me “True”. So if the only change I’ve made is to switch false/true placement, why should it matter? I realized there are something logical I’m missing, so can anybody please explain this to me?

Your code so far

function palindrome(str) {

  str = str.toLowerCase().replace(/[\W_]/g, '');
  for(var i = 0, len = str.length - 1; i < len/2; i++) {
    if(str[i] === str[len-i]) {
      return true;
    }
  }
  return false;
}
palindrome("1 eye for of 1 eye.");

Thanks for reading through my nonsense…:frowning: any help is appreciated guys!
Cheers

5 Likes

Indexes are zero-based. If you have a string of length 10, the first five characters (the first half) will have indexes 0, 1, 2, 3, and 4 (all less than 4.5). It doesn’t have to check for i = 5 because it belongs to the second half.

When looping through strings and arrays with a loop, you’d almost always see i < length - 1 used as the condition when i starts at 0.

If you checked if the two characters are equal in the for-loop, then it would immediately exit the function the moment it sees that two chars from both ends of the string are the same, all while not giving the correct output.

You can’t confirm if a string is a palindrome by just checking if one pair of chars are the same (which is what your modification does). But you can confirm a palindrome by checking if the chars in one pair are not the same. If it can’t find non-matching chars, then you can say that the string is indeed a palindrome.

2 Likes

function palindrome(str) {

let regex=/[A-Za-z0-9]+/g

let target=str.match(regex).join(’’).toLowerCase()

return target==target.split(’’).reverse().join(’’)

}

12 Likes