Palindromes
I think that I will create a small series of posts in which I tackle and explain how to solve common coding questions that one might encounter on a coding interview. Of course, this is good knowledge to have, but it serves the dual purpose of helping me to lay out my thought process, and make sure that I fully understand the problem.
Today's problem is checking whether a given string is a palindrome. A palindrome is a word, phrase, number, or sequence of words that is a mirror of itself. For instance, a common example of a palindrome is "race car." When reversed, the string "race car" is the same as the original string; therefore, it is considered a palindrome. Now, let's see how we can check this using JavaScript.
First, we will define a function that takes in a string as an argument, like such:
function palindrome(str) {
//our code here
}
As for the functionality of the function (I know, the English language, right?), we want the function to return true, if the given string is a palindrome; if the string is not a palindrome, the function will return false.
Solution #1
The first solution that I will work through for the purpose of this exercise is very straight-forward, but may not be the best at demonstrating a strong command of JavaScript and using certain methods and helpers.
Step 1
Naturally, to check whether a string or sequence is a palindrome, we must first compare each element, or at least have the elements separated so that we can analyze them. In this solution, we will rely on a timeless classic: the split method. I will give a sample string to visualize this better. It will look something like this:
let str = 'abba';
function palindrome(str) {
let splitStr = str.split('');
return splitStr
}
console.log(palindrome(str)) => ['a','b','b','a'];
Step 2
Now, we have an array that represents each element in the string that was passed into the function. It stands to reason that, if we were simply looking at the string that we are given, "abba", we can easily see that reversing the string would give us the same result; this is, in fact, a palindrome. So, how do we represent this with code? Well, we are going to combine 2 quick steps here. We have an array, and we want the inverse of that array. Simple enough: we can use the reverse method. However, just calling the reverse method on this array will give us the reversed array, not the reversed string. Once again, we call on a familiar friend: join. So, we first reverse the array that we created using the split method in step one, and then join the array into a single string. We are left with the following:
Note: I am replacing the variable name from step one to reflect the new changes.
let str = 'abba';
function palindrome(str) {
let reversedStr = str.split('').reverse().join('');
return reversedStr
}
console.log(palindrome(str)) => 'abba';
Step 3
Finally, now that we have the reversed string, or the mirror of the original string, we need to do a simple comparison to see whether the reversed string is directly equal to the original string. Here, we are going to use a strict equality (===) comparison operator to create a boolean value, which will return either true or false. I am choosing to use the strict equality comparison, because we want to make sure that the result is a comparison of type string. In other words, we do not want to make an error in manipulating the string, and potentially converting the string into another data type. The final solution should look like the following:
let str1 = 'abba';
let str2 = 'acdb';
function palindrome(str) {
let reversedStr = str.split('').reverse().join('');
return str === reversedStr
}
console.log(palindrome(str1)) => true;
console.log(palindrome(str2)) => false;
This seems simple enough. We took the string, split it into an array, reversed the array, joined the reversed array into a single string, and compared the original with the reversed string. If they were equal, then the given string is a palindrome; if not, then the string is not a palindrome. The above solution relies on simple methods and principles. Let's dive into a more-complex solution.
Solution #2
In this solution, we will make use of the every method, which can be applied to arrays. This is a little bit more leg-work, but is a good exercise to demonstrate your understanding of the every method and array manipulation.
领英推荐
Step 1
The first step in this approach is the same as above: we split the string into an array, which we will then compare. Pretty simple.
let str = 'abba';
function palindrome(str) {
let splitStr = str.split('');
return splitStr
}
console.log(palindrome(str)) => ['a','b','b','a'];
Step 2
Now, we will call the every method on the split string. This method checks whether each element in the array meets a specified test or check, and returns a boolean value. The logic is the same as the first solution; we are just implementing a different strategy.
The every method takes in two arguments in this case:
So, the first part of the function using every looks like so:
Note: char represents each character, or element, of the string as an array.
function palindrome(str){
return str.split('').every((char, i) => {
//our conditional check
})
}
Step 3
Now, to put the final touches on this function. We simply need to do a comparison of each element to the element in the mirror position in the array. To clarify, if we use our example string, 'abba,' the first character 'a' is at index 0, and it's mirror is the last element in the array, which is at index 3. In order to do this comparison, we must specify the index of the element on which we are operating, which we do in passing i into the every method, and the index of the element in the original string to which we are comparing. This gets a bit tricky, and took a while for me to conceptualize. I will try to break it down.
let str = 'abba';
console.log(str[0]) => 'a';
console.log(str[3]) => 'a';
return str[0] === str[3] => true;
As we can see from the above, we do find that the first character of the string (array) is equal to its counterpart at index 3. Moving onto the second character in the array, which has an index of 1, we compare to its mirror character. In this case, its mirror is directly next to it, at index 2, like so:
let str = 'abba';
console.log(str[1]) => 'b';
console.log(str[2]) => 'b';
return str[1] === str[2] => true;
Now, to create a conditional that will test each element and its mirror, we do the following. We use our length method on the original string to count the number of characters in the string (array). Next, we subtract the index of the current element from the length of the array, which gives us the index of the element that we will compare to its mirror. Finally, we subtract 1 from this number, which gives us the position of the mirror element.
function palindrome(str){
return str.split('').every((char, i) => {
return char === str[str.length - i - 1]
})
}
Just to show what is actually going on under the hood, I will put in the actual characters and their indices rather than the placeholders. For the first element and its mirror (first iteration), the function will look like the following:
function palindrome('abba'){
return str.split('').every(('a', 0) => {
return 'a' === ['a','b','b', 'a'][4 - 0 - 1]
)
}
}
As we can see, the element at index 0, 'a,' is equal to the element at index (4 - 0 - 1 = 3). Naturally, this approach is slightly more complicated, as it involves running checks on each element in the array, rather than taking the inverse and comparing it as a whole. You can decide which one is better!
I know that this has been a rather lengthy explanation, but I hope that it helps with the concept of string and array manipulation. Happy Coding!