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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code