Approaching a Palindrome Algorithm

Natalia Wit
2 min readJan 4, 2021

--

A palindrome is a word, phrase, or sequence that reads the same backward as forward. For example, if we reverse the word dad, it will still read as the word dad.

We will be approaching a problem where we have to find out if the given string is a palindrome or not, if it is we will return true otherwise, return false.

Let’s get started:

--- DirectionsGiven 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. *Do* include spaces and punctuation in determining if the string is a palindrome.--- Examples://   palindrome("dad") === true//   palindrome("hey") === falsefunction palindrome(str) {}

Approach Steps:

  1. Reverse a string that is provided to us.
  2. Compare the string to the reversed string to return true or false
Palindrome — Solution 1

What we are doing above is setting a variable reversed to a string that is given to us and reversing it. .split() method gives us back an array of each of the characters of the string. In order for us to use the .reversed()method on our given string, we needed to convert it into an array since it’s an array method. We then used the .join() method to join the characters back together and outputs a string. Let me show you all of this under the hood with a string that is not a palindrome so you can understand it better:

let reversed = "cool"reversed.split('')
=> [ 'c', 'o', 'o', 'l' ]
[ 'c', 'o', 'o', 'l' ].reverse()
=> [ 'l', 'o', 'o', 'c' ]
[ 'l', 'o', 'o', 'c' ].join('')
=> 'looc'

After that, all we really needed to do is to do a direct comparison of the reversed variable to the given string by using === operator which checks for a boolean value and return it.

Conclusion:

It’s important to note that this is not the only way you will solve this problem. There are many more approaches/solutions and this is just one of them. Practicing a few different approaches may be beneficial for you while interviewing. Check out these array methods which can help you with coming up with different solutions.

Resources:

Array Methods — MDN

--

--