A clear guide to solving Length of Last Word by scanning the string from right to left.
Problem Restatement
We are given a string s containing English letters and spaces.
We need to return the length of the last word in the string.
A word is a maximal substring made only of non-space characters. The string contains at least one word. The official constraints are 1 <= s.length <= 10^4, and s contains only English letters and spaces.
Input and Output
| Item | Meaning |
|---|---|
| Input | A string s |
| Output | Length of the last word |
| Word | A maximal substring of non-space characters |
| Spaces | May appear before, between, or after words |
Function shape:
def lengthOfLastWord(s: str) -> int:
...Examples
For:
s = "Hello World"The last word is:
WorldIts length is:
5So the answer is:
5For:
s = " fly me to the moon "The trailing spaces do not count.
The last word is:
moonThe answer is:
4For:
s = "luffy is still joyboy"The last word is:
joyboyThe answer is:
6First Thought: Split the String
A simple solution is to split the string into words and return the length of the last word.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
words = s.split()
return len(words[-1])This works because Python’s split() without arguments ignores extra spaces.
For example:
" fly me to the moon ".split()produces:
["fly", "me", "to", "the", "moon"]Then the last word is easy to read.
Problem With Split
The split solution is valid, but it creates a list of all words.
We only need the last word. Building every word uses extra memory.
A direct scan from the end avoids that extra allocation.
Key Insight
The last word is closest to the end of the string, but there may be spaces after it.
So we scan from right to left:
- Skip trailing spaces.
- Count non-space characters.
- Stop when we reach a space before the last word.
This reads only what is necessary.
Algorithm
Start from the last index:
i = len(s) - 1First, skip spaces at the end:
while i >= 0 and s[i] == " ":
i -= 1Then count the last word:
length = 0
while i >= 0 and s[i] != " ":
length += 1
i -= 1Return length.
Correctness
After the first loop, i points to the last non-space character in the string. Since the input contains at least one word, such a character exists.
The second loop moves left while the current character belongs to the last word. It increments length once for each character in that word.
The loop stops when it reaches either the beginning of the string or the space before the last word. Therefore length equals exactly the number of characters in the last word.
Complexity
| Metric | Value | Why |
|---|---|---|
| Time | O(n) | In the worst case, we scan the string once from right to left |
| Space | O(1) | We store only an index and a counter |
Implementation
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == " ":
i -= 1
length = 0
while i >= 0 and s[i] != " ":
length += 1
i -= 1
return lengthCode Explanation
We begin at the final character:
i = len(s) - 1The first loop skips spaces after the last word:
while i >= 0 and s[i] == " ":
i -= 1Now i is at the last character of the last word.
Then we count characters until we hit a space:
length = 0
while i >= 0 and s[i] != " ":
length += 1
i -= 1Finally, return the count:
return lengthTesting
def run_tests():
s = Solution()
assert s.lengthOfLastWord("Hello World") == 5
assert s.lengthOfLastWord(" fly me to the moon ") == 4
assert s.lengthOfLastWord("luffy is still joyboy") == 6
assert s.lengthOfLastWord("a") == 1
assert s.lengthOfLastWord("a ") == 1
assert s.lengthOfLastWord("single") == 6
assert s.lengthOfLastWord("many spaces") == 6
print("all tests passed")
run_tests()| Test | Why |
|---|---|
"Hello World" | Basic two-word input |
" fly me to the moon " | Leading, middle, and trailing spaces |
"luffy is still joyboy" | Last word at the end |
"a" | Smallest word |
"a " | Trailing space after one word |
"single" | Only one word |
"many spaces" | Multiple spaces between words |