freeCodeCamp Basic Algorithm: Reverse a String

When you are a new programmer, the term ‘algorithm’ is shrouded in mystery. The mere mention of it triggers an ominous sense of dread.

Despite what you might think, algorithms aren’t indecipherable puzzles that only people with Computer Science degrees can solve.

Don’t get me wrong, there are some incredibly difficult algorithms out there but you aren’t likely to encounter those as a new programmer.

The algorithms you are going to face can usually be solved with a solid understanding of JavaScript.

This will be the first in a series of articles where we break down algorithms from freeCodeCamp’s Basic Algorithm Scripting section.

Basic Algorithm Scripting challenges

As I mentioned earlier, we are going to use JavaScript to solve these problems.

You should be comfortable with JavaScript and the different methods for working with strings and arrays before tackling these challenges.

The Problem

The first algorithm we are going to cover is called Reverse a String.

Here is a quick description of the problem and the code we are given to start.

Reverse a String algorithm instructions

We are provided a string, seen in the code block above, which we need to reverse and then return.

We are also given a nice clue about converting the string to an array. Most importantly, we are given links to several methods that might be of use in solving this problem.

Last, but not least, we see several more string examples and what they should return when reversed. Our solution needs to successfully reverse all of these examples.

Some of these challenges aren’t written very clearly. Looking at the different examples and the expected results is often the best way to understand exactly what it is that you need to do.

Read the Documentation

All these challenges include helpful links. Some of these links are more helpful than others.

In this case, we are given links to the exact methods that we will need to use to solve the problem.

The one exception is Global String Object.

By this point, you should already know what a string is. If you don’t, you should probably keep working on your JavaScript and revisit algorithms at a later date.

String.prototype.split()

The first method we get a link to is String.prototype.split(). If you haven’t already, click on that link and check out the documentation for that method.

This first line tells us the .split() method splits a string into an array by separating the string into substrings.

This is perfect since we need to convert the string to an array anyway.

We could have done that by creating a variable to store the new array but now we don’t have to. The .split() method will automatically convert the string to an array during the splitting process.

If we scroll down in the documentation, we can read about the syntax and see some examples using the method.

Spoiler alert: if you scroll down far enough in the documentation you will find the solution to this challenge. You could just copy/paste that code but you won’t learn anything that way. Keep reading and I will explain how everything works.

At the very beginning of the Syntax section, there is a tip that tells us exactly what we need to know.

Hint for .split() method

There are several different separators you can use with the .split() method but we want to use .split(“”) for this problem.

To see this method in action, change ‘return str;’ to ‘return str.split(“”);’ in the code box and hit the Run Tests button.

You should see [“h”,”e”,”l”,”l”,”o”] in the console below the Run Tests button.

This is exactly what we want. The original string has been converted to an array as shown by the [] and each item has been separated.

Array.prototype.reverse()

The next method on our helpful hint list is Array.prototype.reverse().

If you look closely at how the two methods are named there is a clue for why we needed to convert the string to an array.

Bonus points to you if you noticed that one starts with ‘String’ and other starts with ‘Array’.

The .reverse() method only works on arrays and there isn’t a similar method for working with strings. That is why we had to convert the string to an array.

If you haven’t already, click on the link above to access the documentation.

The first line informs us that the .reverse() method reverses an array in place. The first element in the array becomes the last, and the last element becomes the first.

Sounds like exactly what we need.

Let’s add it to the end of ‘return str.split(“”);’ like so ‘return str.split(“”).reverse();’ and hit the Run Tests button again.

Now you should see [“o”,”l”,”l”,”e”,”h”] in the console below the button.

All we need to do now is combine the split items and turn it back into a string.

Can you guess how to do that?

Array.prototype.join()

The last link on our helpful hint list points us towards Array.prototype.join(). The name certainly sounds promising.

Click on the link above and let’s see what the documentation has to say about .join().

Once again, the first sentence tells us exactly what we need to know. The .join() method joins all elements of an array into a string.

If you continue to scroll down and check out the syntax and examples sections you will see that .join() also uses a separator just like the .split() method.

Let’s use the same separator we used for .split() and add .join() to the end of the solution we have been working on. Your code should now look like this:

Reverse a String algorithm solution

Hit the Run Test button and see what happens.

You should receive some type of celebratory popup letting you know that you have successfully solved the algorithm. Congratulations!

If you didn’t get this message you will need to go back to your code and try to find the error.

Lessons Learned

This algorithm was pretty simple in that we were given links to the exact methods that we needed to use to solve the problem. We won’t always be handed the answer like this.

That is where Google comes in.

If you do a search for ‘javascript string to array’ the first result that comes up is the documentation for the .split() method. The same goes for reversing an array. Search for ‘javascript reversing an array’ and documentation for .reverse() tops the list.

From there, it is just a matter of reading the documentation and figuring out how to use the method. This is a valuable skill for a programmer as much of your time is going to be spent reading documentation to figure out how something works.

Keep in mind that these challenges can be solved many different ways.

I mentioned earlier that we could have created a variable to convert the string to an array. If you went that route your code might look something like this:

Alternative solution to the Reverse a String algorithm

This was actually the first solution I came up with for the problem.

I didn’t realize that the different methods could be chained together in one line of code or that you could call the methods directly on the str argument in the return statement.

If you have questions about this algorithm or the methods that were used just drop me a line in the comment section.

Have fun and keep coding!

Sharing is caring!

Author: Lee

Hi, my name is Lee and I am a 40-something who recently made the decision to become a self-taught programmer. This site was set up to chronicle that journey and my experiences along the way. Feel free to contact me with any comments, questions, or suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *

8 − 2 =