Length of Last Word
EasyGiven a string s
consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
Explanation
The key insight for this problem is that we need to find the last word in the string, not the first. The most efficient approach is to traverse the string backwards from the end.
Algorithm: Reverse Traversal
By starting from the end of the string, we can efficiently skip trailing spaces and count the characters of the last word:
- Start from the last character of the string
- Skip all trailing spaces by moving the pointer left until we find a non-space character
- Count the characters of the last word by moving left until we hit another space or the beginning of the string
- Return the count
This approach is optimal because we only traverse the string once and only examine the relevant portion (the end of the string), making it O(n) time complexity with O(1) space complexity.
Idea Map
Initialize i = len(s) - 1
Skip trailing spaceswhile s[i] == ' ': i--
Mark end of last wordend = i
Count word lengthwhile i >= 0 and s[i] != ' ': i--
end - i
Complexity Analysis
Time Complexity
O(n) - In the worst case, we traverse the entire string once, where n is the length of the string. However, we typically only examine the trailing portion.
Space Complexity
O(1) - We only use a constant amount of extra space for pointers and counters, regardless of the input size.
Code
def lengthOfLastWord(s: str) -> int:
Initializes the function `lengthOfLastWord` which takes a string `s` as input and returns an integer representing the length of the last word.
i = len(s) - 1
Sets pointer `i` to the last index of the string (0-indexed, so length minus 1).
length = 0
Initializes a counter `length` to keep track of the word length.
while i >= 0 and s[i] == ' ':
Skips trailing spaces by moving the pointer left while the current character is a space. This handles strings with trailing spaces.
i -= 1
Decrements the pointer to move to the previous character.
while i >= 0 and s[i] != ' ':
Now counts characters of the last word by continuing to move left while we see non-space characters.
length += 1
Increments the length counter for each character in the last word.
i -= 1
Moves to the previous character to continue counting.
return length
Returns the calculated length of the last word.
public int lengthOfLastWord(String s) {
Initializes the function `lengthOfLastWord` which takes a String `s` as input and returns an integer.
int i = s.length() - 1;
Sets pointer `i` to the last index of the string.
int length = 0;
Initializes a counter `length` to keep track of the word length.
while (i >= 0 && s.charAt(i) == ' ') {
Skips trailing spaces by moving the pointer left while the current character is a space.
i--;
Decrements the pointer to move to the previous character.
}
End of the trailing space skipping loop.
while (i >= 0 && s.charAt(i) != ' ') {
Now counts characters of the last word by continuing to move left while we see non-space characters.
length++;
Increments the length counter for each character in the last word.
i--;
Moves to the previous character to continue counting.
}
End of the word counting loop.
return length;
Returns the calculated length of the last word.
}
End of the function.
int lengthOfLastWord(string s) {
Initializes the function `lengthOfLastWord` which takes a string `s` by value and returns an integer.
int i = s.size() - 1;
Sets pointer `i` to the last index of the string using `size()` method.
int length = 0;
Initializes a counter `length` to keep track of the word length.
while (i >= 0 && s[i] == ' ') {
Skips trailing spaces by moving the pointer left while the current character is a space. Note: `i >= 0` check comes first to avoid out-of-bounds access.
i--;
Decrements the pointer to move to the previous character.
}
End of the trailing space skipping loop.
while (i >= 0 && s[i] != ' ') {
Now counts characters of the last word by continuing to move left while we see non-space characters.
length++;
Increments the length counter for each character in the last word.
i--;
Moves to the previous character to continue counting.
}
End of the word counting loop.
return length;
Returns the calculated length of the last word.
}
End of the function.
Edge Cases & Common Mistakes
Warning: Trailing spaces
The most common mistake is not handling trailing spaces. Always skip spaces from the end before counting the word length. Input "Hello World " should return 5, not fail or return incorrect values.
Tip: Empty string
The problem guarantees at least one word exists, but you should still handle the case where the string might be empty or contain only spaces gracefully by returning 0.
Best Practice: Single word
When the input is just one word without spaces (e.g., "Hello"), your algorithm should correctly return the length of that entire word. The reverse traversal handles this naturally.
Related Problems
Understanding String Parsing
String parsing is a fundamental skill in programming. It involves extracting meaningful information from text by identifying patterns, delimiters, and structures. From processing CSV files to building compilers, string parsing is everywhere.
Learn more about string parsing →Disclaimer: This problem is for educational purposes. Practice the 'Length of Last Word' problem on LeetCode.