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 a maximal substring consisting of non-space characters only.

Input & Output

Example 1 — Basic Case
$ Input: s = "Hello World"
Output: 5
💡 Note: The last word is "World" which has length 5
Example 2 — Trailing Spaces
$ Input: s = " fly me to the moon "
Output: 4
💡 Note: The last word is "moon" which has length 4, ignoring trailing spaces
Example 3 — Single Word
$ Input: s = "luffy"
Output: 5
💡 Note: Only one word "luffy" with length 5

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of only English letters and spaces ' '

Visualization

Tap to expand
Length of Last Word Problem"Hello World Programming"↓ Find last wordProgrammingLast wordCount characters: P-r-o-g-r-a-m-m-i-n-gLength: 11
Understanding the Visualization
1
Input String
String with words separated by spaces
2
Identify Last Word
Find the rightmost word ignoring trailing spaces
3
Count Length
Return the character count of last word
Key Takeaway
🎯 Key Insight: Work backwards from the end to avoid processing the entire string unnecessarily
Asked in
Apple 12 Microsoft 8
287.5K Views
High Frequency
~10 min Avg. Time
1.8K 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