Algo Logging: Reverse a String in JavaScript
Tags: javascript, beginners, algorithms, tutorial
Published: 2021-12-07 22:27:40

Welcome back! 

I am starting to work my way through [this repository of algorithm problems](https://github.com/learn-co-curriculum/postwork-data-structures-and-algorithms) from Learn-Co. It starts off easy, which is great for people who may be new to algorithms.

So, I thought I could, _ahem_, re-start at the beginning, too. I know I have previously presented some more challenging problems, but I'm headed back to basics for a bit.

If you'd like to try the problem yourself first, you can find it in the above linked repository or here:

[CodeWars](https://www.codewars.com/kata/5168bb5dfe9a00b126000018)
[LeetCode](https://leetcode.com/problems/reverse-string/)*

_* This version is slightly different in expectation. More on this later._
___
## The Problem 

The __Reverse String__ algorithm problem is as follows:
>*Given a string `s`, return `s` in reverse. Do not use any built-in reverse method.*

### Example

>`s` *=* `hello world`
*output =* `dlrow olleh` 

___
## The Approach

Before I get into my approach, I need to address the LeetCode version of this problem, which asks for you to solve the problem "in-place", meaning "mutate the original string." 

I am solving these problems in JavaScript, and in JavaScript, [strings are immutable](https://developer.mozilla.org/en-US/docs/Glossary/Mutable). This means it is _not possible to reverse a string in-place_. There's a reason the LeetCode version of this problem has to use an array of characters instead of a string. Since an array of strings is not itself a string, and our our problem is **how to reverse a string**, not an array, that is the problem we will solve. 😤

```js
const a = "I'm a string";
const b = ['I', "'", 'm', ' ', 'n', 'o', 't'];

typeof(a) === 'string'; //true
typeof(b) === 'string'; //false 🤯
Array.isArray(b); //true 🤯
```
<figcaption>Apparently, an array is not a string.</figcaption>

That being said, if the problem you are given is to reverse an array in-place, (which is what the LeetCode version of this problem is,) the solution I am going over here is not the most optimized version. Check out the two-pointer technique, instead.

__Okay, back to the program.__

In this approach, we will initialize a new variable, `reversed`, as an empty string. We will then loop over `s` backwards, adding each character to `reversed` inside of the loop. 

**Time Complexity**: O(n)
{% collapsible Why? %}
There is a single `for` loop. The time it takes to compute the solution will grow directly with the length of our input string, `s`. Thus, `n` represents the length of `s`.
{% endcollapsible %} 

**Space Complexity**: O(n)
{% collapsible Why? %}
We are creating a variable, `reversed`, that will be the length of `s`. This means the memory consumed to solve the algorithm is directly related to the length of `s`. Thus, `n` represents the length of `s`.
{% endcollapsible %} 

### Variables Used:

* `reversed` - An empty string to which we will add characters from `s`.
* `i` - Our `for` loop counter. It will initially point to the last index of `s` so we can loop backwards.

___

### Line-by-Line Walkthrough:

```js
function reverseString {...}
```

1. Initialize variable `reversed` as an empty string {% collapsible show %}```js
 let reversed = "";
  ``` {% endcollapsible %} 

2. Create a `for` loop which will iterate through the length of `s` backwards. Initialize variable `i` with value of `s.length-1`, set the loop exit condition to be when `i` is equal to `0`, and decrement `i` each iteration. Backwards looping! {% collapsible show %}```js
for (let i = s.length-1; i >=0; i--) {...
``` {% endcollapsible %} 

3. Inside of the loop, redefine `reversed` to be `reversed` + the current character we are at in `s`. {% collapsible show %}```js
    reversed += s[i]
``` {% endcollapsible %} 

4. Once the loop has finished, return `reversed`. {% collapsible show %}```js
    return reversed
``` {% endcollapsible %} 
___
## Show Me The Logs

Here are my console.logs for this problem.

__For the best experience, view them on [replit](https://replit.com/@raquii/ReverseAString?v=1), where you can fork it and feed your own inputs into the function!__

```js
🚀 🚀 🚀 REVERSE A STRING STARTING NOW 🚀 🚀 🚀
__________________________________________________

        📥 s = "hello world"

============ LOOP 1 OF 11 ============

            s = "hello world"
            reversed = ""
            i =  10 
            s[i] = "d"
            
============ LOOP 2 OF 11 ============

            s = "hello world"
            reversed = "d"
            i =  9 
            s[i] = "l"
            
============ LOOP 3 OF 11 ============

            s = "hello world"
            reversed = "dl"
            i =  8 
            s[i] = "r"
            
============ LOOP 4 OF 11 ============

            s = "hello world"
            reversed = "dlr"
            i =  7 
            s[i] = "o"
            
============ LOOP 5 OF 11 ============

            s = "hello world"
            reversed = "dlro"
            i =  6 
            s[i] = "w"
            
============ LOOP 6 OF 11 ============

            s = "hello world"
            reversed = "dlrow"
            i =  5 
            s[i] = " "
            
============ LOOP 7 OF 11 ============

            s = "hello world"
            reversed = "dlrow "
            i =  4 
            s[i] = "o"
            
============ LOOP 8 OF 11 ============

            s = "hello world"
            reversed = "dlrow o"
            i =  3 
            s[i] = "l"
            
============ LOOP 9 OF 11 ============

            s = "hello world"
            reversed = "dlrow ol"
            i =  2 
            s[i] = "l"
            
============ LOOP 10 OF 11 ============

            s = "hello world"
            reversed = "dlrow oll"
            i =  1 
            s[i] = "e"
            
============ LOOP 11 OF 11 ============

            s = "hello world"
            reversed = "dlrow olle"
            i =  0 
            s[i] = "h"
            

======== 🏁 Finished Looping 🏁 ========
  
        🌟 🌟 🌟 Final Solution 🌟 🌟 🌟

 The reversed version of "hello world" is "dlrow olleh"!
```
___
## Solution

Finally, if you'd like to see a clean, log-free version of the solution, here it is:

{% spoiler View Solution %}
```js
function reverseString(s) {
  let reversed = "";

  for (let i = s.length - 1; i >= 0; i--) {
    reversed += s[i]
  }

  return reversed;
}
```
{% endspoiler %}

Thanks for reading and I wish you luck on whatever algorithmic endeavor brought you to this post. ♥