DEV Community

Cover image for I will have the last word.
Natalie Hummel
Natalie Hummel

Posted on • Edited on

I will have the last word.

Or at least, the number of letters in it, using this LeetCode challenge (#58) solution. My cohort colleague, Chay, and I paired up to tackle this one in JavaScript. Let's take a look at the rules:

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only.

If you've ever done a LeetCode challenge, you know how talented they are at coming up with ALL KINDS of examples to test against your code. Your three-line solution becomes an 'if' statement becomes an 'if / else if / else' statement. Words and characters you've never dreamt of come out of the woods to test your code and your patience. This challenge was no exception.

We knew we'd need to find a way to call the last element in the array. But to get there, we needed a workable array. Taking string s, we used .split(' ') to break up the words. We experimented in the console and found we were on the right track. Using their starter code:
var lengthOfLastWord = function(s) { }
and their example #1, s = "Hello World!":
Alt Text

We got the length of the last word! First example is a success. After the splitting worked, giving us two items in an array (and its length, 2), we were able to subtract one from the total array length to give us the last word of the array ("World"). Grabbing the length of that, we have 5. Alert the press!

Onward to example #2: s = " "! Originally, we wanted to account for this value as a part of the if/else statement:

if (s === "") { 
       return 0
    } 
Enter fullscreen mode Exit fullscreen mode

But through the hidden examples, we realized we didn't account for s = " (many spaces) " and other such madness. Fortunately, while I was talking to the invisible duck in this blog post, I realized I could shorten my original solution and use the same code for example #1. Thanks, duck!

var lengthOfLastWord = function(s) {
    let words = s.split(' ')
    let lastWord = words[words.length-1].length
    return lastWord
}
Enter fullscreen mode Exit fullscreen mode

This works for both their provided examples. Done, right? Not quite. We were thrown a curveball with s = "a ". Well shoot, someone got lazy or crazy. Time to regroup and Google how to trim whitespace. Enter the .trim(), a groovy little method that weeds out the lazy/crazy whitespace in a string. Its siblings, trimEnd (aka trimRight) and trimStart (aka trimLeft), allow you to trim before and after the "legible" content, should you need more specific trimming. Since we need to account for all possibilities, we better use regular trim. We added it to the very beginning of the function to prevent more surprise-space heartbreak:

var lengthOfLastWord = function(s) {
    let trimTheFat = s.trim()
    let words = trimTheFat.split(' ')
    let lastWord = words[words.length-1].length
    return lastWord
}  
Enter fullscreen mode Exit fullscreen mode

This current solution won't work, though. When we split "a ", we are left with ["a", ""]. We have two items in this array and one is not welcome. Technically, the last official word of the original string is "a". We gotta pop that last "" off! Let's use .pop(), shall we? If the last element in the "words" array is "", we'll pop it off the end and return words without it.

var lengthOfLastWord = function(s) {
    let trimTheFat = s.trim()
    let words = trimTheFat.split(' ')
    if (words[words.length-1] === ""){
        words.pop()
        return words.length
    } else {
        let lastWord = words[words.length-1]
        return lastWord.length
    }
}
Enter fullscreen mode Exit fullscreen mode

One caveat-- .pop() is a destructive method, which means it changes the construction of the original array. That is why when we returned "words" after the pop, it returned the array without our dangling double quotes. I was fine with a little destruction, as it was not specified in the instructions and I was getting hungry.

After several examples were tested, we submitted the solution and it passed. Chay and I were elated and felt like developer gods. Reminder-- this was an easy challenge. It didn't take a lot to get us excited. But for a couple of students new to this crazy world, I think we did a-ok.
Alt Text

Top comments (0)