scan from the end
Starting at the last index means the first non-space character found is part of the answer. No need to process the entire string or split into tokens.
A chat application displays conversation snippets, showing the last word of each message
as a preview tag — but messages can end with stray spaces from pasted text, auto-correct,
or speech-to-text. Finding the true last word means scanning from the end: skip any
trailing spaces, then count characters until you hit a space or the start of the string.
No splitting, no allocation. O(n) time. O(1) space.
The last word lives at the right edge of the string. A reverse scan reaches it immediately, avoiding irrelevant prefix characters entirely.
Starting at the last index means the first non-space character found is part of the answer. No need to process the entire string or split into tokens.
Phase one: skip trailing spaces (length still zero). Phase two: count non-space characters (length grows). The transition happens naturally when the first letter appears.
Once counting has started, the next space marks the left boundary of the last word. Everything before it — leading spaces, earlier words — is irrelevant and never examined.
A single reverse loop with one counter and one branch handles all cases.
Begin at i = s.length − 1. The counter length starts at zero.
Trailing spaces are noise. While s[i] is a space and no letters have been counted yet, move left.
Every non-space character belongs to the last word. Increment length and continue left.
A space after counting means the word's left boundary is found. Break and return length.
Some inputs skip an entire phase, making the scan even shorter.
When the string ends with a letter, the skip phase is empty. Counting begins immediately at the last character — no wasted iterations.
With no spaces at all, the count phase runs to the start of the string. The boundary is the string's own left edge, and the length equals the string length.
A single non-space character between two spaces means the count phase fires exactly once. The very next character is a space boundary — length is 1.