String manipulation problems like “Length of Last Word” are frequently asked in interviews at companies like Google, Amazon, and Microsoft because they test your ability to handle edge cases, work with string traversal, and write clean, efficient code. This problem focuses on reverse string traversal and demonstrates how a simple two-pointer approach elegantly handles trailing spaces without requiring extra memory allocation.
Problem statement
Given a string s that contains words separated by spaces, return the length of the last word in the string. A word is defined as a maximal sequence of consecutive non-space characters. The string may contain leading or trailing spaces, but you need to identify the last valid word and return its length.
Constraints:
- 1 <=
s.length<= 104 sconsists of only English letters and spaces' '.- There will be at least one word in
s.
Examples
| Input | Output | Explanation |
"Hello World" | 5 | The last word is "World" which has 5 characters. |
" fly me to the moon " | 4 | Despite trailing spaces, the last word is "moon" with 4 characters. |
"programming" | 11 | The entire string is one word with 11 characters. |
Naive approach
The most intuitive approach would be to split the string into words using the built-in split() method, store all words in an array, and then return the length of the last element. While this approach works correctly and handles all edge cases like trailing spaces and multiple spaces between words, it’s not optimal for this specific problem.
This approach has a time complexity and space cmplexity of O(n), where n is the length of the string. While the time complexity is acceptable, the space complexity is unnecessary. We’re using extra memory to store all words when we only care about the last one. This becomes problematic when dealing with very long strings that contain many words. For example, we’d be allocating memory for hundreds or thousands of words just to use information about the final one.
Optimized approach using reverse string traversal
The key insight is that we don’t need to process the entire string or store any words. We only need to find and measure the last word. By traversing the string from right to left (reverse direction), we can skip any trailing spaces first, then count characters until we hit another space or reach the beginning of the string. This approach is elegant because it naturally handles trailing spaces without any special case logic.
We use a two-pointer technique where we track our current position while moving backward through the string. First, we skip all trailing spaces by moving our pointer left until we find a non-space character. Then, we count consecutive non-space characters until we encounter a space or reach the start of the string. This gives us the length of the last word directly without needing to identify or store any other words.
This works even with multiple trailing spaces because we explicitly skip all spaces at the end before we start counting. Once we find the first non-space character from the right, we know we’re at the end of the last word, and we simply count backward until that word ends.
Step-by-step algorithm
- Initialize a variable
ito the last index of the string. - While
i >= 0and the characters[i]is a space:- Decrement the value of
ito move one position to the left.
- Decrement the value of
- Initialize a counter variable
lengthto0to track the length of the last word. - While
i >= 0and the characters[i]is not a space:- Increment the
lengthcounter . - Decrement the value of
ito move one position to the left.
- Increment the
- After computing the length of the last word of the string, return the value of
length.
Code implementation
Let’s look at the following code to understand its implementation.
Code for the length of last word problem
Time complexity
The time complexity of this algorithm is O(n), where n is the length of the string. In the worst case, we might need to traverse the entire string if it consists of only spaces followed by a single word at the beginning (e.g., " word"). However, in many practical cases, we’ll only traverse a small portion of the string from the right. We make a single pass from right to left, performing constant-time operations (character comparison and counter increment) at each step, giving us linear time complexity.
Space complexity
The space complexity of this algorithm is O(1) because we only use a constant amount of extra space regardless of the input size. We maintain just two integer variables (i for the current index and length for the word length), and we don’t create any additional data structures, such as arrays or strings.
Common pitfalls and interview tips
- Forgetting to skip trailing spaces: Many candidates start counting from the end immediately, without first skipping trailing spaces. This leads to incorrect results for inputs like
"hello world ". Always handle trailing spaces before starting your word count. - Off-by-one errors with index bounds: When traversing backward, make sure your loop condition is
i >= 0, noti > 0. If the last word starts at index 0, you need to include that character in your count. Test with edge cases like"a"or"word"to verify your boundary conditions. - Overcomplicating with string manipulation: Some candidates try to reverse the string, use regular expressions, or build substrings. These approaches work but introduce unnecessary complexity and, in some cases, worse space complexity. The simple two-pointer reverse traversal is cleaner, more efficient, and demonstrates better algorithmic thinking in an interview setting.