Algorithms and Data Structures Part I

Photo by Markus Spiske on Unsplash

If you’re like me and somewhat new to the coding world let me just tell you, STUDY ALGORITHMS!!! they are so important. Algorithms usually pop up in technical interviews and are used everyday by developers. So with that in mind let's get started…

String Reversal

For this problem you are given a string and asked to reverse it then return it as a new string. Ok so let’s get started. First we need a function…

Now there are a few ways to tackle this problem but this is the easiest way…

We will be using the reverse() method. This method is used to reverse an array and we have been given a string but luckily we have a method to turn our string into an array, reverse it and then turn it back into a string.

So we are going to:

  1. Turn ‘str’ into an array.
  2. Call the ‘reverse’ method on the array.
  3. Join the array back into a string.
  4. Finally return the result (Very Important!).

So here we create a variable that I’ve named arr and we take ‘str’ and call .split(“”) on it. This will turn our string into an array. Now that we are working with an array, we can call that reverse() method…

and now that the array is reversed we can turn that array back into a string with the .join(“”) method…

and we have a reversed string. Lastly we need to return the result…

and that’s basically it!

We can tidy this code up a bit though and instead of creating a variable at all we can do the following…

Here we return our str with .split(“”).reverse().join(“”) all called on it directly and we get the same result with three lines of code instead of five.

In part II, knowing what we’ve learned here we will talk about palindromes and integer reversal all using the .split(“”).reverse().join(“”) method.

Thank you for reading.

Learning to code, one day at a time.