Length of Last Word
Measure the final word by scanning backwards, skipping trailing spaces first
Problem Statement
Given a string s consisting of words separated by spaces, return the length of the last word. A word is a maximal run of non-space characters.
Input: "Hello World"
Output: 5
Input: " fly me to the moon "
Output: 4 ("moon")
Input: "luffy is still joyboy"
Output: 6 ("joyboy")Intuition
The one-liner is tempting: split on spaces, take the last piece, return its length. It works — but it builds a list of every word when you only need one, and it has to handle the empty strings that trailing spaces produce.
The key insight
The last word is at the end, so start there.
- Walk backwards past any trailing spaces.
- Then count non-space characters until you hit a space or the start of the string.
You touch only the trailing spaces plus the last word — never the rest of the string.
The two phases must be separate. Trying to count and skip in one loop is what produces the classic bug on inputs like "hello ", where a naive scan reports 0.
Watch it run
Approach
Phase 1 — skip trailing spaces
Decrement while the current character is a space.
Phase 2 — count the word
Decrement while the current character is not a space, incrementing a counter.
Solution
def length_of_last_word(s: str) -> int:
"""Length of the final word in s."""
i = len(s) - 1
# Phase 1: skip trailing spaces.
while i >= 0 and s[i] == " ":
i -= 1
# Phase 2: count the word's characters.
length = 0
while i >= 0 and s[i] != " ":
length += 1
i -= 1
return lengthThe built-in version, which is perfectly acceptable and very readable:
def length_of_last_word_split(s: str) -> int:
words = s.split() # split() with no argument drops empty pieces
return len(words[-1]) if words else 0A split trap in JavaScript
"a b ".split(' ') returns ["a", "b", "", ""] — the trailing spaces produce empty strings, so words[words.length - 1] is "" and the answer would be 0.
Python's "a b ".split() (no argument) collapses whitespace and drops empties, returning ["a", "b"]. The two languages behave differently here, which is why the TypeScript version needs .trim() and a regex.
Complexity Analysis
Time Complexity
O(n)
Space Complexity
O(1)
- Time — worst case
O(n)when the string is one long word or mostly trailing spaces. Typically far less, since only the tail is examined. - Space — two integers. The split versions allocate
O(n)for the word list, which is the practical reason to prefer the backwards scan.
Edge Cases
Related Problems
- Reverse Words in a String — the same whitespace handling, applied to every word
- Valid Palindrome — scanning a string from both ends
- Longest Common Prefix — character-level string scanning