## DEV Community

Jyothikrishna

Posted on • Updated on

# Leetcode question 58 Length of Last Word js solution

We can break the problem into 3 subproblems

• Removing trailing spaces if they exist
• Finding the words present in that processed string
• And finally finding the length of the last word present in the processed string

We will tackle this subproblems one at a time.

## Step 1 : Removing whitespaces at the beginning and end of the string

Since the string given to us might contain whitespaces in it, we need to remove them because if we don't remove them js treats them as different words.

To achieve this we make use of the `trim` method

``````const sWithOutWhiteSpaces = s.trim()
``````

## Step 2 : Finding words present in string given

This step is very easy to do. We use `split` method achieve this.

``````const wordsInS = sWithOutWhiteSpaces.split(" ")
``````

## Step 3 : Finding the last word in given string

Last word present in given string is the last element in array `wordsInS`. Length of that word is our required answer.

``````const lastWord = wordsInS[wordsInS.length - 1]
return lastWord.length
``````

Total solution

``````var lengthOfLastWord = function (s) {
const sWithOutWhiteSpaces = s.trim();
const wordsInS = sWithOutWhiteSpaces.split(" ");
const lastWord = wordsInS[wordsInS.length - 1];
return lastWord.length;
};

``````

If you submit at this point you will get these stats

## Optimization

We can optimize the time and space required to run this program by chaining all the methods and make it into a single statement thereby reducing the amount of space used by our program since we are no longer using memory to store intermediate values linke wordsInS.

Now our solution looks like this

``````var lengthOfLastWord = function (s) {
return s.trim().split(" ").pop().length;
};
``````

## Time and space complexity

• Time: O(n)
• Space: O(1)

After doing above mentioned optimizations you will get these stats

I hope you found this article. If yes hit that like button.

Happy Hacking