Last Updated: March 29, 2026
We need to find the length of the last word in a string. Sounds simple, but there's a catch: the string can have trailing spaces. "Hello World " has the last word "World" (length 5), not an empty string.
So the real task is: skip any trailing spaces, then count characters backward until you hit another space or the beginning of the string. That count is your answer.
1 <= s.length <= 10^4 → With n up to 10,000, even O(n^2) would be fine. But this problem naturally has O(n) solutions, so there's no reason to overthink complexity.s consists of only English letters and spaces → No special characters, tabs, or newlines to worry about. Simplifies parsing.s → We're guaranteed a valid answer exists. No need to handle the "no words" edge case.The most natural first thought: split the string into words and grab the last one. Most languages have a built-in split function that handles multiple spaces between words. After splitting, the last element of the resulting array is the last word, and its length is the answer.
There's a small nuance though. Some language's split functions may include empty strings in the result when there are trailing spaces, depending on the implementation. We need to be aware of this, but in most cases, splitting by spaces and picking the last non-empty word does the trick.
s by spaces.Input:
After splitting: words = ["fly", "me", "to", "the", "moon"]
Last word is "moon", length = 4:
This approach works correctly but processes the entire string and allocates extra memory.
What if we started from the end and just counted the characters of the last word directly?
Since we only care about the last word, why process the string from the beginning? Starting from the end, we can skip trailing spaces, then count non-space characters until we hit a space or the start of the string. That count is our answer.
This approach reads only as many characters as needed. For "Hello World", we only look at the last 5 characters plus however many trailing spaces there are. The earlier part of the string is never touched.
The two-phase scan exploits the fact that we only need information about the last word. By starting at the end, we avoid processing the entire string. Phase 1 handles the trailing spaces edge case. Phase 2 counts the word. The i >= 0 guard in both loops prevents going out of bounds if the entire string is one word with no leading spaces.
This is a common technique for string problems: when you need something at the end of a string, scan backward.
i and length). No extra data structures.