Bonfire: Find the Longest Word Solution

We’re looking for the longest word in a string today and slowly getting more familiar with how to approach algorithms by breaking down problems in a human readable fashion. Remember in math tests when you would have to come up with equation to solve a word problem? Those typically went something like: “Jack has two apples and decides to split them to share with his friends Alissa and George. If George gets 3/4 of an apple and Alissa gets 2/3 of an apple, how much apple does Jack have left?”

Not the greatest word problem up there, but hopefully you get the gist. Writing algorithms for programs isn’t too much different than interpreting and coming up with solutions for math word problems. You essentially have to break things down into logical steps and approach the problems one step at a time. Finding the longest word in a string is a good exercise to really break down this thought process.

Approaching the Problem

Free Code Camp’s Bonfire starts you off with this:

function findLongestWord(str) {

    return str.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

You have a function, you have a string fed into that function and the task is to locate the longest word within that string and return how many characters are in it. If you’re proficient with English, you already know the answer to this without having to write a program to solve it, the longest word is ‘jumped’ and it has 6 characters. But how do we approach this answer programmatically?

Let’s think about what we’re tasked to do here. We have to find the longest word in a sentence. If you were asked to do that normally, this is what you would probably do to come to the conclusion–without using an programming, just basic problem solving skills:

  1. You would look at the sentence.
  2. You would look at each individual word and count how many letters are in each.
  3. You would compare your letter counts for each word and determine which word has the most characters.
  4. You would name which word you discovered to have the most letters–and therefore, is the longest word, and declare how many letters it has.

Already, we’ve laid out a game plan to write our algorithm to solve this problem in four steps. If we took our problem solving solution above and translated it to JS pseudocode, we might have an approach that looks like this.

  1. Take in the string via the function. Split the string into an array at each space. This will allow for counting and comparison because strings are immutable and arrays can be manipulated.
  2. Set a longestWord variable that is empty to use as a comparison variable when we compare each of the words. Eventually load this variable with the longest word discovered in the string.
  3. Loop through the words contained within the split up array and compare each word to determine which one has the most characters.
  4. Set the longest word into the longestWord array and return the character count value of the longest word discovered while looping.

Finding the Longest Word With a Loop & Conditional

So we have a logical approach and a bunch of pseudo code. Let’s head into the actual code now and approach this one step at a time. I’ve double checked this approach because I wasn’t too sure about it and I was pretty much on the right track. I refined what I had my notes to more closely match these two solutions: Gorka Hernandez’ Solution and Alexandrebvd’s Solution

First thing’s first, we know we have to split up our string into manageable chunks. Specifically, we need an array that holds each word within our sentence. Therefore, we need a way for the array to use split(), and split() should know to create a new array at each space it encounters in the string.

A Quick Note About Substrings

Within the split() method, we can specify that the string be split at each space by dividing it up into substrings. In very simple terms, a substring is a portion or part of a string. So if you had a string that was, “Andy likes apples”, then some examples of substrings for that string would be “Andy” “likes” “apples” or “And” “yli” kes” “app” “les” and so on. Substrings are useful because you split strings up in various ways to manipulate them, check them, and more.

For this particular exercise, we actually do need to split our string up into substrings, and using the split() method we can specify that it substrings our string based upon spaces. That is to say, every time split() encounters a space, it will create a new substring.

So our string: “The quick brown fox jumped over the lazy dog”

Will be substringed using split() into: “The” “quick” “brown” “fox” “jumped” “over” “the” “lazy” “dog”

Notice above that we’ve split the sentence into individual words. That’s exactly what we want in order to count each of those words. So let’s dive back into the code and split our string up:

function findLongestWord(str) {

var splitStrArray = str.split(' ');

return str.length;
 }
findLongestWord('The quick brown fox jumped over the lazy dog');

In the code above, I’ve created an array called splitStrArray. That array is going to be populated with substrings that are a result of whatever str is when each of its components has been split every time the split() method encounters a space in str. Please note the space between the two quotes. This space is very important because it tells split() where we want it to split our string up.

Next thing I’m going to do is create an empty string variable that will hold whatever the longest word will be. This will also be the variable that we perform checks on using our loop and the variable we’re going to use to return the character count to validate the exercise:

function findLongestWord(str) {

var splitStrArray = str.split(' ');
var longestWord = '';

return str.length;
 }
findLongestWord('The quick brown fox jumped over the lazy dog');

longestWord is set to nothing right now, because it will be filled with whatever our loop discovers to be the longest word in the string. Now that we have the set up out of the way, we’ve satisfied the first two steps in our pseudocode/problem solving steps. Our next step is to write out our loop:

function findLongestWord(str) {
  
  var splitStrArray = str.split(' ');
  var longestWord = '';
  
  for (var i = 0; i < splitStrArray.length; i++) {
    
  }
  
  return longestWord.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

This for loop is pretty standard right now, and in the old track on Free Code Camp, when we were still going through Code Academy’s JS course, they’ve had us loop through an array a few times. A few of those times to check the length, or to iterate through the array looking for a specific character or word. We’re doing a similar thing above in that we’re looping through the splitStrArray’s substrings based on the length of each substring or word that was pulled from str.

Right now all we’re doing is looping through each substring. We’ve validated a part of step 3, so we need to finish it off by counting each of the substrings we’re looping through, loading the words it finds into longestWord, and then checking each longestWord against each substring to find the longest word or substring. We can accomplish this using a simple if conditional nested inside of our for loop. Incidentally, this is also our finalized code:

function findLongestWord(str) {

    var splitStrArray = str.split(' ');
    var longestWord = '';

    for (var i = 0; i < splitStrArray.length; i++) {

        if (splitStrArray[i].length > longestWord.length) {
            longestWord = splitStrArray[i];
        }

    }

    return longestWord.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

Up there, we’ve got a if statement that checks the total length of each substring in the splitStrArray array against the longestWord string’s length. If if finds a word within splitStrArray that is longer than whatever longestWord’s length is, then it changes longestWord to that word. It continues to do this and perform the check until it loops through all of the substrings within splitStrArray. At which point, it should have the longest word while at the same time, have checked through the entire array.

The Step Through

Here’s the step through for a better visual of what’s happening:

Pass 1:
splitStrArray[0] = “The”
longestWord = “”
splitStrArray[0] > longestWord = true
set longestWord = splitStrArray[0]
longestWord = “The”

Pass 2:
splitStrArray[1] = “quick”
longestWord = “The”
splitStrArray[1] > longestWord = true
set longestWord = splitStrArray[1]
longestWord = “quick”

Pass 3:
splitStrArray[2] = “brown”
longestWord = “quick”
splitStrArray[2] > longestWord = false
longestWord = “quick”

Pass 4:
splitStrArray[3] = “fox”
longestWord = “quick”
splitStrArray[3] > longestWord = false
longestWord = “quick”

Pass 5:
splitStrArray[4] = “jumped”
longestWord = “quick”
splitStrArray[4] > longestWord = true
set longestWord = splitStrArray[4]

longestWord = “jumped”

Pass 5:
splitStrArray[5] = “over”
longestWord = “jumped”
splitStrArray[5] > longestWord = false
longestWord = “jumped”

Finally at the end of splitStrArray, it should evaluate the last substring in the array which would be “dog”, the if statement will evaluate to false because the length of “dog” is shorter than the length of “jumped”. The loop exits because there are no more substrings to evaluate or iterate through and the function will return the length of the longestWord string variable, which in this case should be “jumped”. Jumped has six characters, so its length should return as “6”. The Bonfire will validate and pass.

Resources

Gorka Hernandez Blog, Finding the Longest Word
Gorka also explores this Bonfire solution using functional programming in addition to the loop solution. The alternative solution involves the use of reduce. Good for a bit of tinkering if you’re interested in jumping ahead or getting into the functional programming concept.


Posted

in

by

Comments

5 responses to “Bonfire: Find the Longest Word Solution”

  1. Collyn

    This is my solution.

    function findLongestWord(str) {
    str = str.split(‘ ‘);
    var longestWordLength = 0;
    for (var x in str) {
    if (str[x].length > longestWordLength) {
    longestWordLength = str[x].length;
    }
    }
    return longestWordLength;
    }

    findLongestWord(“The quick brown fox jumped over the lazy dog”);

    1. Awesome job, Collyn! Thanks for sharing your solution.

  2. Bruce

    Hi Bonfire,

    Thank you so much for posting this breakdown of your solution. I was looking at a solution to this problem written in Ruby and understand the reasons behind some of the steps. Your verbal explanation and step-through of each loop really made it clear 🙂

    Thanks!

    1. You’re very welcome, Bruce! Thank you for stopping by and leaving a comment.