Algorithm Practice: Reverse Word walkthrough

Marlon
10 min readAug 4, 2020

--

This one wasn’t so bad. Wild draw 4 could end any relationship

I’m excited to write another algorithm walk-through. This problem is a little simpler than my previous post but don’t let it fool you, it has a really nice pattern that tricked me when I first started programming. It’s a simple pattern, but probably something really nice to keep under your belt. If you haven’t checked out my previous post go check it out: ransom note — walkthrough

Problem Description:

The function will take a string as a parameter, reverse every word in that string and return a new string with the reversed words. Keep in mind that we do not want to reverse the order of each word in the string itself.

Example:

// Initial string
Stay hungry stay foolish
// 1. 2. 3. 4.
// What we want
yatS yrgnuh yats hsiloof
// 1. 2. 3. 4.
// What we don't want
hsiloof yats yrgnuh yatS
// 4. 3. 2. 1.

In the example “What we don’t want”, it shows that we have the order of each word in the string also reversed.

Time for your game plan

counting cards

As cool as it may seem we can’t plan like Alan like that, maybe in a few years with a lot of practice (I hope). For now let’s get our friends pen and paper and pseudocode first. You don’t have to pseudocode every single step of the problem, specially if you’re not used to it yet. Just try for 5 minutes and then try to break the problem apart.

  1. Try a simple string, something with 2 words. Getting in the habit of simplifying your problem as much as you can will give you something to start with and will help you build your confidence on the way.
  2. Use the information given by the problem to guide you to the solution or improvise. If you’re given any examples: first identify if it’s easy enough to get you to a simple solution. If it’s not a simple example, then simplify it to limit the amount of constraints (limit number of if’s and but’s). If not much is given and you don’t have someone to ask more questions, just create an example of a simple input to guide you to a simple output.
  3. Ask a bunch of questions: how could you get that simple output? what had to happen for those letters to be moved? how can you move words around? how can you move letters around? what are the number of words in a string? what are the number o letters in a word? should you make it into an array?
  4. Move pieces around and don’t be shy to make your notes look ugly.
Just write it all down

Let’s break it down

Step 1:

Let’s declare a function with one parameter.

function reverseWords(myString) {
// let's check if we have our string
console.log(myString)
}reverseWords("Stay hungry stay foolish")

Keep the habit to console.log-ing from the get go. It sounds simple, but when I started out I can’t tell you how many times I had a typo in my arguments or variables passed in to my functions that were not being read. We’re not particularly bug masters in the beginning so I think it’s a good thing to keep in mind always (personal preference).

Let’s get our simple input from above again (“Apple Pie”) and let’s look at our words isolated again:

What are the ways we know we can get to this?

Step 2 :

We’re looking at each word separately. User .split(“ “) to split your string into an array of words, where each word is an element of the array.

function reverseWords(myString) {
let wordsArr = myString.split(' ');
console.log(wordsArr)
}
reverseWords("Stay hungry stay foolish")

You should have a value like this returned. That looks a lot with what we have in our “Apple Pie” example, but in code:

[ 'Stay', 'hungry', 'stay', 'foolish' ]

Step 3:

The next step is to iterate over that array of words to be able to manipulate each word individually.

function reverseWords(myString) {let wordsArr = myString.split(' ');

// iterate over each word of your array
wordsArr.forEach(word => {
console.log(word) });
}
reverseWords("Stay hungry stay foolish")

Let’s see what we have in our wordsArr:

Stay
hungry
stay
foolish

Step 4:

We have all the words we need. The next step is to reverse each each character of each word, correct? Let’s see how that looks with a simple example:

Simple result of the words reversed

It seems like we need to move each one of those characters around. The same way we were able to loop over each word in our string and return them, let’s try to loop over each character of each word. Let’s visualize it:

Each word and its characters

A simple pattern to know in programming is to be able to loop through an array or a hash table (which we tend to use another kind of loop instead) and have access to each one of its elements (or key/values). Below we are doing the exact same thing we did to see each word but we’re using a different kind of loop.

function reverseWords(myString) {let wordsArr = myString.split(' ');wordsArr.forEach(word => {  for (let i = 0; i < word.length; i++) {
console.log(word[i])
};
});
}
reverseWords("Stay hungry stay foolish")

Notice that we’re using the .length property to return the length of each word. So in that example you have

i = 0 word //=> let's say "Apple"word.length //=> 5 => the length of the word Apple is the total of
// characters it contains
i++ //=> will increase the value of i by 1 each time the code block
// finishes executing
i < word.length // => this condition will allow the value of i
// to be increased until it reaches the total length
// of the current word being looped.

You also must’ve noticed that we have a forEach (outer loop) looping through an array of words and another loop, the for loop (inner loop), going through each one of those words and printing out each character.

This looks like document from the late 90's — I tried

I hope this diagram can help you understand what is happening each step of the way. I changed the array to [“pie”, “crust”] so it was easier to work with a 3 character word.

If we console.log all the elements (characters) from within that word variable we should get the following:

S
t
a
y
h
u
n
g
r
y
s
t
a
y
f
o
o
l
i
s
h

Now we have access to each character of each word. Having access to each character plus the flexibility of the for loop we can experiment with our code in many different ways.

Note: If you’re just starting out and attempted this challenge before without having a lot of practice you probably found yourself scratching your head and wondering how to experiment with your code. Well, just move stuff around until it breaks! That’s how you do it. It’s very important not to fear trying things out when we’re learning. Try it out and see if it works, if it doesn’t you can always Ctrl + Z and go back to how it was. Don’t forget to combine your experiments with the knowledge you possess so you can make educated attempts along the way.

Let’s check one last time those ideas from above and move those letters around within their own length of characters.

This should give an idea for our next steps

Remember how you want your final answer to look like and think of a way to translate that into code.

Now get up, stretch your legs and go get some water. If this is a little overwhelming it’s just because you’re not yet familiar with a pattern or two. If you can move on, go to the next step, otherwise, take a 3 minutes break. It will also help you internalize it. You’ve done great so far!

Step 5:

The reason I was trying to highlight that nested loop to prepare you for the changes it will receive.

We’re going to loop over each character of each word… BACKWARDS.

function reverseWords(myString) {let wordsArr = myString.split(' ');wordsArr.forEach(word => {    // we're counting each word down and reversing the logic
for (let i = word.length-1; i >= 0; i--) {
console.log(word[i])
};
});
}
reverseWords("Stay hungry stay foolish")

Play around with this code and try to understand what it’s doing. Refer back to that funky diagram I made and see if it helps you understand what we’re doing.

i = word.length-1

=> The Length still 5 but we subtract 1 from the length of the word because “i” will start counting from the index 0. So it will go from 0, 1, 2, 3, 4, 5 — or 6 iterations — that’s because strings behave sort of like arrays. Although “Apple” has 5 letters so we don’t need to iterate 6 times, but only 5 (Go ahead and experiment with it a little bit).

i--

=> We’re going to decrement the value of “i” because this time we’re going from the total number of characters down to 0.

i ≥ 0

=> The condition will also change since we have a “i” with a high value and we want to display those values backwards.

y
a
t
S
y
r
g
n
u
h
y
a
t
s
h
s
i
l
o
o

It’s a little hard to tell but if you pay attention you can see that we still have the words in the original order but we managed to display the characters backwards with our little trick i = word.length-1 — remember that because that may come handy to you one day.

Step 6:

Let’s collect those characters and put them somewhere to see what we got.

function reverseWords(myString) {let wordsArr = myString.split(' ');// Create an array to store the characters.
let resultReversed = []
wordsArr.forEach(word => { for (let i = word.length-1; i >= 0; i--) {

// store each character in an array
resultReversed.push(word[i])
};}); console.log(resultReversed)
}
reverseWords("Stay hungry stay foolish")

hmmm…

[
'y', 'a', 't', 'S', 'y', 'r', 'g', 'n', 'u', 'h', 'y', 'a', 't',
's', 'h', 's', 'i', 'l', 'o', 'o','f'
]

Not quite. But we’re getting close (Try to find the words).

Step 7:

Remember your string concatenation lessons?

let greeting = "Hello"
let separation = ", "
let noun = "World"
let saySomething = "";
saySomething += greeting += separation += noun//=> Hello, World

Let’s apply the same technique to our problem.

function reverseWords(myString) {let wordsArr = myString.split(' ');
let resultReversed = []
// create a string to store our characters
let
eachWord = ""
wordsArr.forEach(word => {
for (let i = word.length-1; i >= 0; i--) {
eachWord += word[i]
};
});
console.log(eachWord)
}
reverseWords("Stay hungry stay foolish")

We’re pushing each character to our new string for every iteration of our for loop.

yatSyrgnuhyatshsiloof

It looks like we’re getting super close but we’re no longer using our resultReversed array. If you pay attention we already have the correct sequence and the reversed value of the words, but the problem is that we are storing every single character next to each other. Our words have no way to know when they begin and when they end.

Step 7:

Let’s move things around again a bit:

function reverseWords(myString) {let wordsArr = myString.split(' ');
let resultReversed = []
wordsArr.forEach(word => { // create a string to store our characters
let eachWord = ""
for (let i = word.length-1; i >= 0; i--) {
eachWord += word[i]
};

// move the console.log inside the forEach
console.log(eachWord)
});
}
reverseWords("Stay hungry stay foolish")
  1. Between the forEach (outer loop) and the for loop (inner loop) the eachWord variable will be initialized for each iteration of the forEach loop.
  2. Inside the for loop we’re concatenating all the characters of the CURRENT word we are looping from the forEach to the eachWord variable.
  3. When the for loop (inner loop) ends we print out the current value of eachWord variable
  4. Repeat step 1.
yatS
yrgnuh
yats
hsiloof

Step 8:

Finally, instead of just console.log-ing those values we will store them in that array we created a few steps back.

function reverseWords(myString) {let wordsArr = myString.split(' ');
let resultReversed = []
wordsArr.forEach(word => {
let eachWord = ""
for (let i = word.length-1; i >= 0; i--) {
eachWord += word[i]
};
// push each value to the array and join them
resultReversed.push(eachWord)
}); return resultReversed.join(" ")
}
reverseWords("Stay hungry stay foolish")
  1. Push the value of eachWord variable to resultReversed array at the end of each iteration of the forEach.
  2. Join all those words with a “ “ (space) in between and return resultReversed array.

We’re done — Thank you!

I hope I was able to help you see through this problem if you were stuck or simply gave you a better understanding of a few of the many patterns in algorithm problem solving. You’re not the only one learning, I really enjoy trying to breaking down these problems, reinforce and practice these patterns. Check out my previous blog post here.

If you enjoyed this walkthrough and think someone could benefit from it, please share with a friend. Oh! since I have your attention, if you really liked it, give me a few thumbs up too.

— Thank you again :)

If you want more practice go over to freecodecamp and checkout their algorithms section.

--

--

No responses yet