Problem 58

Abstract / Summary

Find the number of characters in the last word of a string that does not have leading or trailing spaces but may have spaces between words

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0058.cpp

class Solution {
public:
    int lengthOfLastWord(string s) {
        stringstream m;
        m.str(s);
        int result = 0;
        string word;
        while (m >> word)
            result = word.size();

        return result;
    }
};
13 lines | 255 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (6+ million submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of finding the length of the last word in a given string. It leverages the C++ standard library’s stringstream to tokenize the input based on whitespace, iterates through each token, and keeps the size of the most recent token. When the loop finishes, the stored size corresponds to the length of the last word, which is then returned.

Key Steps

Creating a stringstream from the input

The function begins by declaring a stringstream object and initializing it with the input string. This step prepares the stream for token extraction using the extraction operator (>>).

stringstream m;
m.str(s);

Extracting words sequentially

A loop extracts each whitespace-delimited token into a temporary string variable named word. The extraction operator automatically skips any leading whitespace and stops at the next whitespace character, effectively isolating each word.

while (m >> word)
    result = word.size();

Updating the result with the current word’s length

Inside the loop, the variable result is assigned the size of the currently extracted word. Because the assignment occurs for every token, the final value of result after the loop terminates is the length of the last word encountered.

result = word.size();

Returning the computed length

After the stream has been exhausted, the function returns the stored length.

return result;

Edge Cases Handled

When the input string consists solely of whitespace characters, the extraction operator never succeeds, leaving the loop body unexecuted. In this scenario, result remains at its initial value of 0, which correctly represents the absence of any word.

If the string ends with trailing spaces, the stream’s tokenization naturally ignores those spaces because the extraction operator stops at the last non-whitespace token. Consequently, the length of the final actual word is still captured.

A single-character word or a string containing only one word is processed identically: the loop runs once, result receives the size of that word, and the function returns it.

Multiple consecutive spaces between words are collapsed by the stream extraction, ensuring that only genuine words affect the result.

Performance Optimizations Observed

The algorithm avoids storing all parsed words; it retains only the size of the most recent token. This minimal state reduces memory pressure, especially for long inputs with many words.

Using stringstream provides a built-in, efficient parsing mechanism that operates directly on the underlying character buffer without requiring explicit manual iteration or character-by-character checks.

The single pass through the input-driven by the stream extraction loop-ensures that each character is examined at most once, delivering a streamlined execution path.

Overall, the implementation balances clarity with efficient use of standard library facilities, delivering the desired result with low overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that you have a long, colorful train made of many different toy cars. Each car has a name painted on its side. Your goal is to find the very last car in the train and count how many letters are in its name.

The computer starts by pulling out all the cars one by one. It looks at the first car, reads the name, and keeps that count in its head. Then it looks at the next car. Every time it finds a new car, it forgets the length of the one it just saw and remembers the length of this new one instead. Because it keeps doing this until there are no cars left to check, it ends up remembering only the size of the final car in the line. By the time the train finishes passing by, the computer can tell you exactly how many letters were on that very last car.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.44

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Rust JS Java Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C#
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C#
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
58 links | 40 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Length of Last Word - Leetcode 58 - Python'
NeetCode 7 mins
Length of Last Word - Leetcode 58 - Python
YouTube video 'Length of Last Word (LeetCode 58) | Full solution with examples | Easiest Method'
Nikhil Lohia 11 mins
Length of Last Word (LeetCode 58) | Full solution with examples | Easiest Method
YouTube video 'Length of Last Word | LeetCode 58 | C++, Java, Python'
Knowledge Center 9 mins
Length of Last Word | LeetCode 58 | C++, Java, Python
YouTube video 'Leetcode | 58. Length of Last Word | Easy | Java Solution'
Developer Docs 3 mins
Leetcode | 58. Length of Last Word | Easy | Java Solution
YouTube video 'Length of Last Word | 2 Ways | Leetcode 58 | Amazon | codestorywithMIK'
codestorywithMIK 14 mins
Length of Last Word | 2 Ways | Leetcode 58 | Amazon | codestorywithMIK
YouTube video 'length of last word leetcode | leetcode 58 | string'
Naresh Gupta 6 mins
length of last word leetcode | leetcode 58 | string
YouTube video 'Spotify Coding Interview Question - LeetCode 58 - Length of Last Word'
AlgoJS 7 mins
Spotify Coding Interview Question - LeetCode 58 - Length of Last Word
YouTube video 'LeetCode 58 solution in Hindi | LeetCode Length of Last Word'
Engineering Digest 5 mins
LeetCode 58 solution in Hindi | LeetCode Length of Last Word
YouTube video 'Length of Last Word | LeetCode 58 | Programming Tutorials'
Programming Tutorials 7 mins
Length of Last Word | LeetCode 58 | Programming Tutorials
YouTube video '58. Length of Last Word || Java || Leetcode || Hindi'
Coding Sphere 4 mins
58. Length of Last Word || Java || Leetcode || Hindi
YouTube video 'Length of Last Word - LeetCode 58 - Python #leetcode'
Deepti Talesra 6 mins
Length of Last Word - LeetCode 58 - Python #leetcode
YouTube video 'Length of Last Word | Leet code 58 | Theory explained + Python code'
Sai Anish Malla 3 mins
Length of Last Word | Leet code 58 | Theory explained + Python code
YouTube video 'How To Solve "58. Length of Last Word" on LeetCode - JavaScript Easy'
Becoming A Better Dev (with David) 8 mins
How To Solve "58. Length of Last Word" on LeetCode - JavaScript Easy
YouTube video 'Length of Last Word Python Solution - LeetCode #58'
Professor Oakes 3 mins
Length of Last Word Python Solution - LeetCode #58
YouTube video 'Daily Leetcode #1462: Apr 01, 2024 - 58. Length of Last Word'
Programming Live with Larry 10 mins
Daily Leetcode #1462: Apr 01, 2024 - 58. Length of Last Word
YouTube video '58. Length of Last Word | April | Java | C++'
Mayur Programming Club 9 mins
58. Length of Last Word | April | Java | C++
YouTube video '58. Length of Last Word | Leetcode | Strings | Fundamentals'
Coding with Tamilarasan 9 mins
58. Length of Last Word | Leetcode | Strings | Fundamentals
YouTube video 'Length of Last Word | LeetCode #58 Java Solution | Crack Coding Interview'
SoftWiz Circle 4 mins
Length of Last Word | LeetCode #58 Java Solution | Crack Coding Interview
YouTube video '58. Length of Last Word | 2 Approaches | Brute | Optimal | Easy Explanation | Leetcode'
Rapid Syntax 7 mins
58. Length of Last Word | 2 Approaches | Brute | Optimal | Easy Explanation | Leetcode
YouTube video 'Leetcode | Top Interview 150 | Easy | 58. Length of Last Word | Time: O(N) | Javascript'
Software Interviews Prep 9 mins
Leetcode | Top Interview 150 | Easy | 58. Length of Last Word | Time: O(N) | Javascript
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality