Problem Statement
Length of Last Word
You are given a string s made of words and spaces. Return the length of the last word. A word means a run of characters with no spaces in it, and the last word is the final such run before the string ends (ignoring any spaces hanging off the end).
Signals to notice
Brute force first
Split by spaces, return length of last element — but creates extra strings. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Scan from the end, skip trailing spaces, count characters. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on s = " fly me to the moon "
rstrip → s = " fly me to the moon" (last index 24, char 'n') length=0; i=24 s[i]='n' (not space) → length=1 i=23 s[i]='o' → length=2 i=22 s[i]='o' → length=3 i=21 s[i]='m' → length=4 i=20 s[i]=' ' (space) → break return length = 4
What must stay true
Start from the end to find the last word without processing the entire string. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
s = trimTrailingSpaces(s)
length = 0
for i from last_index down to 0:
if s[i] == ' ': break
length += 1
return lengthPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not handling trailing spaces — 'Hello World ' should return 5. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.