Length of Last Word - Problem

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is defined as a maximal substring consisting of non-space characters only. This means spaces act as delimiters between words, and you need to find the final word before any trailing spaces.

Example: In the string "Hello World", the last word is "World" with length 5.

Note: The input string may contain leading and/or trailing spaces, but you should focus only on the actual words separated by spaces.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "Hello World"
โ€บ Output: 5
๐Ÿ’ก Note: The last word is "World" which has 5 characters.
example_2.py โ€” Trailing Spaces
$ Input: s = " fly me to the moon "
โ€บ Output: 4
๐Ÿ’ก Note: The last word is "moon" (length 4). The trailing spaces are ignored.
example_3.py โ€” Single Word
$ Input: s = "luffy"
โ€บ Output: 5
๐Ÿ’ก Note: There is only one word "luffy" in the string, so it's also the last word with length 5.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • s consists of only English letters and spaces ' '
  • The string contains at least one word

Visualization

Tap to expand
๐Ÿ“š Reading a Book Spine: "Hello World Programming "Hello World Programming๐Ÿ‘‰ Step 1: Start from the right end๐Ÿ‘†Start here!โฌ…๏ธ Step 2: Skip trailing spacesSkip spaces๐Ÿ”ข Step 3: Count the last word backwardsProgramming = 11 chars123...1011๐ŸŽฏ Result: Found last word length11โšก This approach is optimal: we only read as much as needed from the end!๐Ÿ’ก Perfect for long strings where the last word is short
Understanding the Visualization
1
Start from the Right
Begin at the end of the string, like starting from the right side of a book spine
2
Skip Extra Spaces
Move left past any trailing spaces, like ignoring empty space on the spine
3
Count the Last Word
Count each character of the last word until you hit a space
4
Return the Count
You now have the length of the last word without reading the entire spine
Key Takeaway
๐ŸŽฏ Key Insight: Starting from the end eliminates unnecessary processing and naturally handles edge cases like trailing spaces
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
89.5K Views
Medium Frequency
~8 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen