Given a string s of words separated by spaces, return the length of the last word.
A word is a maximal run of non-space characters. The string may have trailing spaces.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given a string s of words separated by spaces, return the length of the last word.
A word is a maximal run of non-space characters. The string may have trailing spaces.
An easy strings problem, graded against 6 test cases (3 of them hidden).
Parsing, comparison, and character-frequency reasoning.
Reach for it when you see: String input where the work is scanning, comparing, or counting characters.
More Strings problems →The obvious solution splits on whitespace, filters out empty strings, and takes the last element. It is correct and perfectly acceptable, but it allocates a list of every word to use exactly one of them.
Scanning from the end is O(1) in space and usually touches only a handful of characters. Two phases: skip any trailing spaces, then count non-space characters until you hit a space or run off the front.
The trailing-space case is the whole difficulty. A solution that starts counting immediately returns 0 for `"day "`, and one that splits naively on a single space produces empty strings that must be filtered - which is why `" a b "` breaks so many first attempts.
A language note worth knowing: Python's `s.split()` with no argument collapses runs of whitespace and drops leading and trailing empties, so `s.split()[-1]` is correct in one line. `s.split(" ")` with an explicit separator does not, and leaves the empty strings in. The difference catches people out well beyond this problem.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.