Length of Last Word: Scanning from the Right
LeetCode 58, Length of Last Word, gives you a string s consisting of words and spaces. Your job is to return the length of the last word. A word is a maximal substring consisting of non-space characters.
For example:
"Hello World"returns5(the last word is"World")" fly me to the moon "returns4(the last word is"moon")"luffy is still joyboy"returns6(the last word is"joyboy")
The approach: scan from the right
The last word sits at the end of the string, so start there. The trick is that the string might have trailing spaces. You need to skip past them before you start counting.
The algorithm has two phases:
- Skip trailing spaces. Start at the last index and move left while the character is a space.
- Count non-space characters. Once you land on a non-space character, keep moving left and counting until you hit a space or reach the beginning of the string.
The count you accumulate in phase two is your answer.
This approach works because you only need the last word. There is no reason to parse the entire string from left to right. Scanning backwards lets you find the answer without processing anything before the last word.
Python's str.rstrip() and str.split() can solve this in one line, but the backwards scan is the technique interviewers want to see. It generalizes to problems where you cannot use built-in string utilities.
The code
def length_of_last_word(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 length
Walk through what happens:
- Set
ito the last index of the string. - The first
whileloop movesileft past any trailing spaces. - Once
ipoints to a non-space character (or has gone below 0), the secondwhileloop counts characters until it hits a space or falls off the left end. - Return
length.
Visual walkthrough
Here is the algorithm running on " fly me to the moon ".
Step 1: Start at the end
length = 0Begin at index 26 (the last character). It is a space, so skip it.
Step 2: Skip trailing space
length = 0Index 25 is also a space. Keep moving left.
Step 3: Found a letter
length = 1Index 24 is 'n'. Start counting. Length = 1.
Step 4: Continue counting
length = 2Index 23 is 'o'. Length = 2.
Step 5: Continue counting
length = 3Index 22 is 'o'. Length = 3.
Step 6: Continue counting
length = 4Index 21 is 'm'. Length = 4.
Step 7: Hit a space, stop
length = 4Index 20 is a space. The last word is complete. Return 4.
The pointer starts at index 26, skips two trailing spaces, then counts four characters (n, o, o, m) before hitting a space at index 20. The answer is 4.
Complexity analysis
| Metric | Value |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(1), only a pointer and a counter |
In the worst case (no trailing spaces, single word), you scan the entire string. In the best case (the last word is short with few trailing spaces), you touch only a handful of characters. Either way, you never allocate extra memory beyond two integer variables.
Building blocks
This problem uses two techniques that show up across many string and array problems.
Reverse scanning
Instead of reading from left to right, you start at the end and move backward. This is the natural approach any time the answer sits near the end of the input. You will see reverse scanning in problems like reversing a string in place, finding the last occurrence of a character, and trimming suffixes.
Trailing space handling
Strings in real-world inputs often have leading or trailing whitespace. The pattern of skipping past it before doing the real work comes up in string parsing problems like atoi (string to integer), trimming inputs, and tokenizing sentences. The key idea is always the same: consume the noise first, then process the signal.
Edge cases
Trailing spaces. The string "hello " has three trailing spaces. The first loop skips them, then the second loop counts "hello" and returns 5.
Single word. The string "hello" has no spaces at all. The first loop does nothing (the last character is not a space). The second loop counts all five characters.
Single character. The string "a" has length 1. The first loop finds a non-space immediately. The second loop counts 1 character and returns 1.
All spaces. While the problem guarantees at least one word exists, if you were to handle the degenerate case of " ", the first loop would move i past all characters. The second loop would never execute, and the function would return 0.
From understanding to recall
You can follow this solution step by step and feel confident you understand it. But two weeks from now, when you sit down for a coding screen, will you remember to handle trailing spaces before counting? Will the two-loop structure come to you automatically?
Spaced repetition bridges that gap. Instead of re-reading the full solution, you drill the individual building blocks (reverse scan, trailing space skip, counting loop) at increasing intervals. After a few reps spread across days, the pattern is locked in long-term memory. When you see a string manipulation problem in an interview, the pieces are already there.
Related posts
- Longest Common Prefix - Another easy string problem that scans characters methodically
- Valid Palindrome - Two-pointer string traversal with character filtering