Palindrome - Challenge 2 (Basic)

clintdev

Clint Maruti

Posted on November 12, 2019

Palindrome - Challenge 2 (Basic)

Okay here's the second post to my guide to understanding the basics of Data Structures and Algorithms with JavaScript series by solving common challenges. On this one, we look at: The infamous Palindrome Challenge.

Question:
Find out if the given string is a palindrome. A palindrome is a string or word that can be read the same in normal and reverse. For example "Madam I'm Adam", "Race Car".

Let's Tackle

  • We will create a function isPalindrome that takes in a string as an argument and returns true if the string is a Palindrome and false if it's not.

  • function isPalindrome(string){
    
    }
    
    Enter fullscreen mode Exit fullscreen mode
  • Next, we will convert the string into a lower case to make it easier for comparison

  • function isPalindrome(string){
      string = string.toLowerCase()
    }
    
    Enter fullscreen mode Exit fullscreen mode
  • We will define a variable and set it to a list of alphabetical letters from a - z. Now, this will help us filter through our string to remove any special characters like comas. We want to only compare letters and not characters. Note, we don't want to use regex

  • function isPalindrome(string){
      string = string.toLowerCase()
      let validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('')
    }
    
    Enter fullscreen mode Exit fullscreen mode
  • Next, we define a variable and set it to an empty array. We then push the valid characters from our strings to the array.

  • function isPalindrome(string){
      string = string.toLowerCase()
      charactersArray = string.split('')
      let validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('')
    
      let lettersArr = []
    
      charactersArray.forEach(char => {
         if(validCharacters.indexOf(char) > -1) lettersArr.push(char)
      })
    }
    
    Enter fullscreen mode Exit fullscreen mode
  • Next, we will join the lettersArr into a string and compare it to its reverse and return true if they match or false if they don't.

  • function isPalindrome(string){
      string = string.toLowerCase()
      charactersArray = string.split('')
      let validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('')
    
      let lettersArr = []
    
      charactersArray.forEach(char => {
         if(validCharacters.indexOf(char) > -1) lettersArr.push(char)
      })
    
      if(lettersArr.join('') === lettersArr.reverse().join('')) return true;
         else return false;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    And, there we have it. Simple isn't it!

    See you at the next one!

    Happy Hacking!!

    💖 💪 🙅 🚩
    clintdev
    Clint Maruti

    Posted on November 12, 2019

    Join Our Newsletter. No Spam, Only the good stuff.

    Sign up to receive the latest update from our blog.

    Related