Length of Last Word
Return the length of the last word in a string, ignoring trailing spaces.
Open on LeetCode ↗Intuition
Splitting on spaces and grabbing the last element feels obviously correct, but it breaks the moment the input has trailing spaces, like 'hello ' - the split produces a trailing empty string as the 'last word', giving length 0 instead of 5. The fix is to stop thinking in terms of split and instead walk from the end of the string: first skip over any trailing spaces to find where the real last word ends, then keep walking backward counting characters until you hit a space or run off the front of the string. That backward walk never materializes an empty token, because it actively skips past the very whitespace that would have created one.
Approach
Skip trailing spaces
Start a pointer at the last index of the string and move it backward while it points at a space character. This lands the pointer on the last character of the actual last word, or moves it off the front entirely if the string is all spaces.
Count backward through the word
From that position, continue moving the pointer backward while the character is not a space (and the pointer hasn't run past index 0). Each step visited is one character of the last word.
Return the count
The distance walked in the counting phase is exactly the length of the last word - no substring needs to be built, just a difference of two indices.
Solution & live demo
Edge cases
Skip past all trailing spaces first so the count starts on the real last character, not an empty token.
The backward walk runs to index 0 (or off the front), counting the whole string as one word.
Only the final run of non-space characters is counted; interior spacing is irrelevant.
Skipping trailing spaces walks the pointer past index 0, so the counting phase never starts and length is 0.