isPalindrome
Lately, I’ve been practicing whiteboard problems to better prepare for technical interviews. There are quite a few popular problems that many companies use to interview Junior Developers and one I’m going to talk about today is “isPalindrome”. A palindrome is a word or phrase that is read the same backwards and forwards. The problem will require you to return ‘true’ if the word is a palindrome and ‘false’ if it is not.
ex. isPalindrome(‘civic’) === ‘true’, isPalindrone(‘honda’) === ‘false
I’m going to explain a simple solution using Javascript.
First we are going to set up a function that takes in a string.
const isPalindrome = (string) => {
console.log(string)}
Then we will place the string inside an array and set it to a variable. This can be done using the split( ) method with single quotes and no space.
const isPalindrome = (string) => {
const reverseString = string.split('')
}
Next we can reverse our array using the reverse( )method.
const isPalindrome = (string) => {
const reverseString = string.split('').reverse()
}
Along the way, be sure console.log everything to make sure you are getting the intended outputs. The next step is to now turn our array back into a string using the join( ) method with single quotes.
const isPalindrome = (string) => {
const reverseString = string.split('').reverse().join('')
}
Now that we have our string reversed, we can compare it to the original string passed in by setting up an ‘if statement’.
const isPalindrome = (string) => { const reverseString = string.split('').reverse().join('') if(string === reverseString){ return true }else{ return false } }isPalindrome(‘civic’)
//output = true
There we have it! But there is a nother way to clean this up a bit using our handy refactoring.
const isPalindrome = (string) => {const reverseString = string.split('').reverse().join('')
return reverseString === string}isPalindrome(‘honda’)
//output = false
Above, we can simply set up a return statement that will return ‘true’ if the ‘reverseString’ and ‘string’ are equal to each other. By default, ‘false’ will be returned if they are not. I hope you find this blog helpful 🤗