In this blog post, I thought I’d go over some simple algorithms that are useful to know as a Javascript developer. While these probably won’t be asked during an interview, the thought process that comes with solving these types of simple algorithms can be used for many of the more difficult questions. We’ll talk about each one and go over some simple solutions. Keep in mind that there are always many different solutions for these questions so feel free to solve them on your own. Your solution may be different than my own. In some cases, I’ll go over more than one solution.
String Reversal
Let’s start with a pretty basic task. Given a string, return a new string with the reversed order of characters. If you’re new to Javascript, you might be thinking that we can call some sort of reverse function on the string and be done with it. Well, there is a reverse function but if you check out the official documentation, you’ll see that it works on arrays and not on strings. With that in mind, it wouldn’t be too difficult to turn the string into an array, reverse it, and turn the array back into a string. As we should with all algorithms, let's write out the steps.
Solution #1
- Turn the ‘string’ argument into an array.
- Call reverse() method on the array.
- Join the array back into a string.
- Return reversed string.
Let’s start coding!
First, we declare a variable arr that takes the str argument and splits it into an array using the string method split().
function reverse(str) { const arr = str.split('') }
Following the split, let’s reverse our new arr array.
function reverse(str) { const arr = str.split('')
arr.reverse();}
In the final step, we can return the arr array joined back into a string using the join() array method.
function reverse(str) { const arr = str.split('')
arr.reverse(); return arr.join('')}
And that's it! Our code looks pretty bulky and confusing so let's chain the methods. After a quick refractor, you’ll notice that I took out the arr declarations and returned the chain statement in one line of code.
function reverse(str) { return str.split('').reverse().join('')}
Solution #2
This second solution will make use of a for loop without using the reverse() method. While using the reverse() method makes things pretty simple, there may be a situation where an interviewer asks use to not “cheat” with the reverse() method. This second solution requires a bit more manual coding but is simple nonetheless.
- Create an empty string reversedStr.
- For each character of string argument, put character at the beginning of reversedStr.
- Return reversedStr variable.
Let’s start by creating our empty string. Remember to use let over const here. The value of const can’t be changed through reassignment and that’s exactly what we're doing in this solution.
function reverse(str) { let reversedStr = '';}
Next, we’ll start our for-loop. More on for..of loops here. Remember, we will be iterating through the string we received as an argument and placing each character at the front of the reversedStr variable. Finally, we’ll return the reversedStr variable.
function reverse(str) { let reversedStr = ''; for (let i of str) { reversedStr = i + reversed; }return reversedStr;}
There you have it. One solution using the reverse() array method and one using a simple for-loop! There are a ton of solutions out there for this simple task and I really encourage you to find some others. While some solutions may be better in terms of efficiency, there is always more than one solution to a specific algorithm.
Palindromes
By definition, Palindromes are words that form the same word if it is reversed. For example, the word “noon” is a palindrome because if “noon” is reversed, it still says and spells “noon”.
Given a string, return true if the string is a palindrome or false if it is not.
Coming off our string reversal practice, this one should be pretty straight forward. In fact, our string reversal method can be used in this algorithm and the next.
- Declare reversed variable that takes str argument and reverses it.
- Compare str argument to reversed variable.
function palindrome(str) { const reversed = str.split('').reverse().join('');}
All that’s left is to compare the reversed variable with our str argument. Remember, all we need to do is return a boolean. Simply return the comparison will work.
function palindrome(str) { const reversed = str.split('').reverse().join(''); return str === reversed;}
Now that we understand how to reverse a string, the solution is pretty simple. Once again, we can refactor this code and remove the variable altogether.
function palindrome(str) { return str === str.split('').reverse().join('')}
Anagrams
One word or phrase is an anagram of another if it uses the same characters in the same quantity.
Check to see if the two provided strings are anagrams of each other.
Let’s go over a couple of solutions. Our first solution will assume that our arguments will be simple, lowercase strings with no special characters, punctuation, or capitals.
Solution #1
The most important part of our first solution will be the sort() array method. More info on sort().
- Split stringA and stringB to an array and assign to variables.
- Sort stringA and stringB.
- Join back into strings.
- Compare and return boolean value.
function anagrams(stringA, stringB) {
const first = stringA.split('').sort().join('')
const second = stringB.split('').sort().join('')
}
In one line, we split each string into an array, sorted the characters using the sort() method, and joined them. Regardless of the word or phrase, if the words are anagrams, they will look the same once sorted.
Finally, we just have to return the boolean comparison.
function anagrams(stringA, stringB) {
const first = stringA.split('').sort().join('')
const second = stringB.split('').sort().join('')
return first === second
}
That was pretty simple but normally, we’d have to account for special characters, capital letters, or any other condition. Let’s account for all of that in the second solution.
Solution #2
In this solution, we’ll make use of regular expressions (regex) combined with the string method, replace(). Regular expressions can be complex and require a blog post of their own but you can refer to the documentation here. We’re also going to use a helper function for fun just to get a better idea of how we're going to “clean” the strings before checking to see if they’re anagrams of each other.
Let’s start with the helper function. We’ll call it cleanString because that is exactly what it is going to do.
function cleanString(string) { return string.replace(/[^\w]/g, "").toLowerCase()}
The replace method uses regex to remove or replace spaces or punctuation so our sole focus will be the characters. We’ll also call toLowerCase() so capital letters won’t be a problem. We still need to sort the letters as we did in our previous solution so let's chain that to our return statement. Remember, we need to split the string into an array in order to sort it and then join it back into a string.
function cleanString(string) {return string.replace(/[^\w]/g, "").toLowerCase().split('').sort().join('')}
Now, we have a function that we can use to “clean” a string. Let’s implement this in our anagrams function.
function anagrams(stringA, stringB) {const compA = cleanString(stringA)const compB = cleanString(stringB)return compA === compB}function cleanString(string) { return string.replace(/[^\w]/g,"").toLowerCase().split('').sort().join('')}
This last part doesn’t need any much explanation. Using the cleanString helper method we created, we created new variables using stringA and stringB. Essentially, we created “clean” versions of these arguments and then compared them!
While we can easily refactor this to not use a helper method, I thought it would be nice to separate them in order to understand what each of the functions is doing.
Conclusion
While there are countless solutions to these simple questions, feel free to tackle them in your own way!