Palindrome Interview Question Solution JavaScript
Tags: javascript, career, tutorial, webdev
Published: 2020-12-31 17:32:22

Another popular interview question is the palindrome test. These solutions are for simple 1 word palindromes. For more complicated palindromes with spaces and punctuation check out this post.

**Disclaimer:** there are MANY ways to solve this problem these are a few answers that I would see or use in a coding interview and would accept as a proper answers

**TLDR:** explanation of best solutions at the bottom and actual solutions at the bottom of each section

## The Problem
Create a function that accepts a string and returns if it is a palindrome.

Example:
```javascript
isPalindrome('Racecar') //true
isPalindrome('mom') //true
isPalindrome('HelloDevWorld') //false
```
## What is a Palindrome
Well knowing what a palindrome is may be a little important. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

## Solutions
For a basic 1 word palindrome what do we need to do?

* create a function that accepts a string

* check if the string is the same forward as it is backwards

    * possible solution is to reverse the string and see if it is equal to the accepted string

    * possible solution check first and last letter for each index and see if they are the same (1 and last, 2 and second to last, etc)

* return true if it is else return false


### Solution 1
Lets solve the first solution like fizz buzz and do it based off our breakdown of the problem so lets start by making our function that accepts a string
```javascript
function isPalindrome(stringToCheck){
    //check if the string is the same forward as it is backwards

    //possible solution is to reverse the string and see if it is equal to the accepted string

    //return true if it is else return false
}
```
Next we have to check if the string is the same forward as it is backwards. we are going to go with the solution to reverse the string to see if it is equal to the string that was passed in. To do this we are going to need to

break up the string into individual characters throw it in an array 

reverse that array

check it against the passed in string

if you don’t know what [.split()](https://www.w3schools.com/jsref/jsref_split.asp), [.join()](https://www.w3schools.com/jsref/jsref_join.asp), [.reverse()](https://www.w3schools.com/jsref/jsref_reverse.asp), or [toLowerCase()](https://www.w3schools.com/jsref/jsref_tolowercase.asp) are check out each W3Schools page (linked on each one) before going further. 

First things first breaking up the string we are going to add a toLowerCase() to the check so that it doesn’t matter if they send in a capitalized letter in the string like in one of the test cases (“Racecar”) if we don’t do this “Racecar” will return as false since “racecaR” does not equal “Racecar”
```javascript
function isPalindrome(stringToCheck){
    const stringArray = stringToCheck.toLowerCase().split("");
    //reverse that array

    //check it against the passed in string

    //return true if it is else return false
}
```
now we need to reverse the array 
```javascript
function isPalindrome(stringToCheck){
    const stringArray = stringToCheck.toLowerCase().split("");
    const reverseStringArray = stringArray.reverse().join("");

    //check it against the passed in string

    //return true if it is else return false
}
```
then check that against the string that was passed in
```javascript
function isPalindrome(stringToCheck){
    const stringArray = stringToCheck.toLowerCase().split("");
    const reverseStringArray = stringArray.reverse().join("");
    const result = reverseStringArray === stringToCheck.toLowerCase();

    //return true if it is else return false
}
```
the return that check you can either do 
```javascript
function isPalindrome(stringToCheck){
    const stringArray = stringToCheck.toLowerCase().split("");
    const reverseStringArray = stringArray.reverse().join("");
    const result = reverseStringArray === stringToCheck.toLowerCase();
    return result
}
```
or my preference would be
```javascript
function isPalindrome(stringToCheck){
    const stringArray = stringToCheck.toLowerCase().split("");
    const reverseStringArray = stringArray.reverse().join("");
    return reverseStringArray === stringToCheck.toLowerCase();
}
```
### Solution 2
Now that we have a basic solution which is a perfectly fine solution lets be developers and make it a 1 liner. cause why not.
```javascript
const isPalindrome = (input) => {
  return input.toLowerCase() === input.toLowerCase().split('').reverse().join('');
}
```
this is exactly the same thing with the same code it is just not split out into variables

### Solution 3
Now lets get a little more complicated and write out the solution for the second possible way of coming up with the solution, check first and last letter for each index and see if they are the same (1 and last, 2 and second to last, etc)

This will be the most performant because we are only comparing up to the middle character and the string isn’t being manipulated other than the lower case. It also fails fast as it will return false quickly (potentially on the first character) if it isn’t the same rather than comparing the whole array to another array it only compares the characters its currently on.

The beginning is the same as last time create a function that accepts a string
```javascript
function isPalindrome(stringToCheck){
    //check if the string is the same forward as it is backwards

    //possible solution check first and last letter for each index and see if they are the same (1 and last, 2 and second to last, etc)

    //return true if it is else return false
}
```
for this solution we will 

* need to loop through the string to check the characters

* for each character in the string

    * check that character against the character in the same spot at the end of the string

        * first and last letter

        * second and second to last letter

    * if they are the same return true otherwise return false

For this loop we only need to loop until the middle character of the string instead of just the whole string since we are comparing the start to the end the whole time by the time we hit the middle we have compared all of the characters. If you don’t know [Math.floor()](https://www.w3schools.com/jsref/jsref_floor.asp), [for loops](https://www.w3schools.com/js/js_loop_for.asp), or [.charAt()](https://www.w3schools.com/jsref/jsref_charat.asp) check out each W3Schools page (linked on each one) before going further. 

we will be using Math.floor() to get the index of the middle character to stop at, for loop to loop through the string, and charAt() to check the character at each index

first we need to loop through the string until the middle character
```javascript
function isPalindrome(stringToCheck){
    for(let i = 0; i < Math.floor(stringToCheck.length/2); i++){

        //check that character against the character in the same spot at the end of the string

        //if they are different return false otherwise continue loop
    }
}
```
now we need to check the character at the index and the opposite index as see if they are different. 

Note: I am doing this in a 1 liner but you could throw stringToCheck.toLowerCase() in a variable and string everything off that variable instead of having stringToCheck.toLowerCase() twice. Either way works
```javascript
function isPalindrome(stringToCheck){
    for(let i = 0; i < Math.floor(stringToCheck.length/2); i++){
       if (stringToCheck.toLowerCase().charAt(i) !== stringToCheck.toLowerCase().charAt(stringToCheck.length-i-1))
        //if they are different return false otherwise continue loop
    }
}
```
then return false if they are different and continue on the loop if they are the same. If the loop ends then we know they are all the same and we can return true.

```javascript
function isPalindrome(stringToCheck){
	for(let i = 0; i < Math.floor(stringToCheck.length/2); i++){
		if (stringToCheck.toLowerCase().charAt(i) !== stringToCheck.toLowerCase().charAt(stringToCheck.length-i-1)) return false
    }
    return true
}
```
We need to do the check this way because if we check that they are equal and return true it will not complete the loop and you will get false positives. This will only break the loop if it fails and then will return true once we are sure they are the same (after the loop has completed) if they are not it will break the loop and return false.

## Conclusion
So which one is the best? I think all answers are just fine. I would never expect a junior developer to come in with solution 3. If they did and were able to explain why it was more performant I would be very impressed. If I were to write it I would write solution 2 this is because I would prefer readability over performance especially on a function that takes up such little processing power. However, if you were asked for the most efficient way especially if they have a large palindrome then solution 3 would be your best bet. in case you were interested here are the metrics for all 3 run by [jsbench](https://jsbench.me/)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9lam8nj6lkzln87w57yv.PNG)