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 - Reverse Iteration INPUT String s: H e l l o _ W o r l d 0 1 2 3 4 5 6 7 8 9 10 Scan direction Input Value: s = "Hello World" Length: 11 characters Words: "Hello", "World" Last word: "World" ALGORITHM STEPS 1 Start from end i = 10 (last index) 2 Skip trailing spaces No trailing spaces here 3 Count word chars While char != space 4 Return count Stop at space/start Iteration Trace: i=10: 'd' count=1 i=9: 'l' count=2 i=8: 'r' count=3 i=7: 'o' count=4 i=6: 'W' count=5 i=5: ' ' STOP FINAL RESULT Last Word Found: W o r l d Output: 5 OK - Verified! "World" has 5 chars Complexity: Time: O(n) Space: O(1) Key Insight: By iterating from the end of the string, we can find the last word in a single pass without splitting or creating new strings. First skip any trailing spaces, then count characters until we hit a space or reach the beginning. This gives us O(1) space complexity! TutorialsPoint - Length of Last Word | Reverse Iteration Approach
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