Length of Last Word – Solution & Complexity
1. Understand What Counts as a Word
- A word is any maximal run of non-space characters.
- Leading, trailing, and repeated spaces should not count as part of a word.
- If the string contains only spaces, the answer is
0.
2. Simple Split-Based Idea
- One straightforward approach is to split the string on whitespace.
- The last token is the last word, and its length is the answer.
- This is easy to read, but it creates a list of all words.
3. Scan from the End
- The last word is closest to the end of the string.
- First skip trailing spaces.
- Then count characters until you reach another space or the beginning of the string.
4. Count the Last Word Characters
- After trailing spaces are skipped,
ipoints at the last character of the last word. - Move left while characters are not spaces, increasing a counter.
- If there was no word, the counter stays at
0.
5. Complete Solution and Complexity
- The final solution uses the end scan to avoid storing extra words.
- Time complexity is O(n) in the worst case.
- Space complexity is O(1).