Level Up Your Coding Skills & Crack Interviews — Save up to 50% or more on Educative.io Today! Claim Discount

Arrow
Table of contents

58. Length of Last Word

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
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Examples

InputOutputExplanation
"Hello World"5The last word is "World" which has 5 characters.
" fly me to the moon "4Despite trailing spaces, the last word is "moon" with 4 characters.
"programming"11The 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.

Why don’t we use split()?

While split() would work, it creates unnecessary intermediate arrays and processes the entire string. Our reverse traversal approach is more memory-efficient because it only uses a constant amount of extra space (a few integer variables) and can potentially terminate early once we’ve measured the last word.

Step-by-step algorithm

  1. Initialize a variable i to the last index of the string.
  2. While i >= 0 and the character s[i] is a space:
    1. Decrement the value of i to move one position to the left.
  3. Initialize a counter variable length to 0 to track the length of the last word.
  4. While i >= 0 and the character s[i] is not a space:
    1. Increment the length counter .
    2. Decrement the value of i to move one position to the left.
  5. After computing the length of the last word of the string, return the value of length.
1 / 7

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

  1. 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.
  2. Off-by-one errors with index bounds: When traversing backward, make sure your loop condition is i >= 0, not i > 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.
  3. 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.

Frequently Asked Questions

What if the interviewer asks us to handle multiple consecutive spaces between words?

Our solution already handles this correctly. The reverse traversal approach naturally skips any number of consecutive spaces, whether trailing or between words. Once we find the last word and start counting, we stop at the first space we encounter, which correctly identifies the word boundary.

Can we solve this problem using the built-in split() method?

Yes, you could use s.split() to get a list of words and return len(words[-1]). This works and is concise, but it has O(n) space complexity because it creates an array of all words. In an interview, it’s worth mentioning this approach, but then explaining why the reverse traversal with O(1) space is more optimal. It shows you can think beyond library functions.

How would we modify this solution if we needed to return the last word itself, not just its length?

We’d use the same reverse traversal approach but build the word as we go. After skipping trailing spaces, we’d track the end position, then continue moving left and store characters. Finally, we’d extract the substring or reverse the characters we collected. The algorithm structure remains the same, only the data we collect changes.

Share with others:

Leave a Reply

Your email address will not be published. Required fields are marked *