Check if a string is a Palindrome

Learning to code

ยท

2 min read

Check if a string is a Palindrome

Given a string, return true if the string is a palindrome or false if it is not. Palindromes are strings that form the same word if it is reversed. Include spaces and punctuation in determining if the string is a palindrome

palindrome('level') // returns true
palindrome('abcde') // reutrns false
palindrome('Learning To Code!') // returns false
palindrome('hi ih') //returns true

Solution 1 - built in functions and compare

  1. Reverse the given string
  2. Compare new reversed string to original string
  3. Return true if string is equal else return false
const palindrome = (str) => {
  return str === str.split('').reverse().join('')
}

Solution 2- Advanced array helper

  1. Split the string into a array
  2. Using the .every array function loop through each character
  3. Check each character (starting from the left/beginning) against its counterpart (starting from the right/end) to see if the characters are equal, continuing sequentially until complete. In the case of odd numbered arrays, this will result in the middle character comparing to itself.
  4. If all characters are equal return true, else return false.
const palindromeCompare = (str) => {
  return str.split('').every((char, i) => {
    return char === str[str.length - i - 1]
  })
}

compare.png

This approach is not as efficient as the first, as it does twice the amount of comparisons that it needs to.

ย