Given a string s consisting of words separated by single spaces, return the length of the last word. A word is defined as a maximal substring of non-space characters.
For example, the last word of "Hello World" has length 5 (World). The last word of "fly me to the moon" has length 4 (moon). The last word of "luffy is still joyboy" has length 6 (joyboy). An empty string returns 0. A single-word string like "Hello" returns 5.
Finding the length of the last word is a classic string problem that tests your ability to parse text efficiently from the end. Instead of splitting the entire string into an array of words (which wastes memory), you can traverse from the rightmost character, skip any trailing spaces, and count until you encounter a space or reach the beginning of the string.
The optimal approach works in one pass from right to left. First, advance past any trailing spaces. Then count consecutive non-space characters until a space or the start of the string is reached. This approach avoids allocating intermediate arrays and uses only a constant amount of extra memory.
Edge cases include an empty string (return 0), a string containing only spaces (return 0, since there are no words), a single word with no spaces (return its length), and a string with multiple trailing spaces (the algorithm must skip them before counting).
Example Input & Output
Last word 'a' has 1
Single word
Empty string
Last word 'moon' has 4
Last word 'World' has 5 letters
Algorithm Flow
Solution Approach
Given a string s consisting of words and spaces, return the length of the last word. Traverse from the end of the string backward, skipping trailing spaces. Once a non-space character is found, start counting until another space or the beginning of the string. This avoids splitting the entire string and uses O(1) extra space.
Two backward loops: first skips trailing spaces, then counts consecutive non-space characters. This handles cases with multiple trailing spaces correctly without needing to trim or split the input.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(String s) {
s=s.trim();return s.length()-s.lastIndexOf(' ')-1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
