Length of Last Word
EasyTop Interview 150 Arrays & HashingProblem
A string s holds words separated by spaces. It may also begin or end with extra spaces.
Return the number of letters in the last word, the final run of non-space characters.
Constraints
- 1 ≤ s.length ≤ 10⁴
- s contains letters and spaces
- s has at least one word
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: Each index is visited at most once, moving right to left, and the scan stops at the word's start.
Space: Only the pointer i and the counter length are stored.
Start at the last character and skip any trailing spaces. Then count letters going left until a space or the start of the string. Nothing before the last word is ever touched.