Facebook Pixel

58. Length of Last Word

EasyString
Leetcode Link

Problem Description

You are given a string s that contains words separated by spaces. Your task is to find and return the length of the last word in the string.

A word is defined as a continuous sequence of non-space characters. The string may have trailing spaces after the last word, which should be ignored when determining the last word.

For example:

  • If s = "Hello World", the last word is "World" with length 5
  • If s = " fly me to the moon ", the last word is "moon" with length 4 (trailing spaces are ignored)
  • If s = "luffy is still joyboy", the last word is "joyboy" with length 6

The solution works by traversing the string from right to left. First, it skips any trailing spaces by moving the pointer i backwards until it finds a non-space character. This marks the end of the last word. Then it continues moving backwards with pointer j until it finds a space or reaches the beginning of the string. The difference i - j gives us the length of the last word.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

When we need to find the last word in a string, the most natural approach is to start from the end rather than the beginning. Why? Because if we start from the beginning, we'd have to traverse through all the words to reach the last one, which is unnecessary work.

Think about how you would manually find the last word if someone showed you a sentence on paper. You'd likely look at the end of the sentence and work backwards until you identify where the last word starts and ends.

The key insight is that we need to handle two scenarios:

  1. There might be trailing spaces after the last word (like "hello world ")
  2. The last word ends exactly at the last character (like "hello world")

So our strategy becomes:

  1. Start from the very end of the string and skip any trailing spaces by moving backwards
  2. Once we hit the first non-space character, we know we've found the end of the last word
  3. Continue moving backwards from this position until we either hit a space (which marks the beginning of the last word) or reach the start of the string

Using two pointers (i and j) to mark these positions allows us to calculate the length simply as the difference between them. This approach is efficient because we only examine the characters we need to - we don't waste time processing the entire string when we only care about the last word.

Solution Approach

The solution implements a reverse traversal with two pointers to efficiently find the length of the last word.

Step-by-step implementation:

  1. Initialize the first pointer i: Start from the last index of the string (len(s) - 1)

  2. Skip trailing spaces:

    while i >= 0 and s[i] == ' ':
        i -= 1

    This loop moves i backwards as long as we encounter spaces. When this loop ends, i points to the last non-space character (the end of the last word).

  3. Mark the end position: Store the current position of i in pointer j:

    j = i
  4. Find the beginning of the last word:

    while j >= 0 and s[j] != ' ':
        j -= 1

    Continue moving j backwards as long as we encounter non-space characters. When this loop ends, j will be at position -1 if the last word starts at index 0, or it will point to the space character just before the last word.

  5. Calculate the length:

    return i - j

    The length of the last word is the difference between i (end of last word) and j (position before the start of last word).

Example walkthrough with s = " hello world ":

  • Initial: i = 13 (last index)
  • After skipping trailing spaces: i = 11 (at 'd')
  • Set j = 11
  • After finding word beginning: j = 5 (at the space before 'world')
  • Length = 11 - 5 = 6 (length of "world")

This approach has a time complexity of O(n) in the worst case where n is the length of the string, and space complexity of O(1) as we only use two pointer variables.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's trace through the solution with s = " fly me ":

Initial state:

  • String: " fly me " (indices 0-9)
  • i = 9 (pointing to the last character, which is a space)

Step 1: Skip trailing spaces

  • i = 9: s[9] = ' ' → move left
  • i = 8: s[8] = ' ' → move left
  • i = 7: s[7] = 'e' → stop (found non-space)

Step 2: Mark the end of last word

  • Set j = i = 7

Step 3: Find the beginning of last word

  • j = 7: s[7] = 'e' → move left
  • j = 6: s[6] = 'm' → move left
  • j = 5: s[5] = ' ' → stop (found space)

Step 4: Calculate length

  • Length = i - j = 7 - 5 = 2
  • The last word "me" has length 2 ✓

Visual representation:

Index:  0 1 2 3 4 5 6 7 8 9
String: _ _ f l y _ m e _ _
                  ^ ^     ^
                  j i   start

The algorithm correctly identifies "me" as the last word by working backwards from the end, skipping the trailing spaces, and finding where the word begins.

Solution Implementation

1class Solution:
2    def lengthOfLastWord(self, s: str) -> int:
3        # Start from the end of the string
4        end_index = len(s) - 1
5      
6        # Skip trailing spaces from the end
7        while end_index >= 0 and s[end_index] == ' ':
8            end_index -= 1
9      
10        # Mark the end position of the last word
11        last_word_end = end_index
12      
13        # Find the beginning of the last word by moving backwards
14        # until we hit a space or reach the start of the string
15        start_index = last_word_end
16        while start_index >= 0 and s[start_index] != ' ':
17            start_index -= 1
18      
19        # Calculate the length of the last word
20        # start_index points to the space before the word (or -1 if at beginning)
21        # so the length is the difference between end and start positions
22        return last_word_end - start_index
23
1class Solution {
2    public int lengthOfLastWord(String s) {
3        // Start from the end of the string
4        int endIndex = s.length() - 1;
5      
6        // Skip trailing spaces from the end
7        while (endIndex >= 0 && s.charAt(endIndex) == ' ') {
8            endIndex--;
9        }
10      
11        // Mark the end position of the last word
12        int startIndex = endIndex;
13      
14        // Move backwards to find the start of the last word
15        // Stop when we encounter a space or reach the beginning
16        while (startIndex >= 0 && s.charAt(startIndex) != ' ') {
17            startIndex--;
18        }
19      
20        // Calculate the length of the last word
21        // startIndex points to the space before the word (or -1 if at beginning)
22        // endIndex points to the last character of the word
23        return endIndex - startIndex;
24    }
25}
26
1class Solution {
2public:
3    int lengthOfLastWord(string s) {
4        // Start from the end of the string
5        int endIndex = s.size() - 1;
6      
7        // Skip trailing spaces from the end
8        while (endIndex >= 0 && s[endIndex] == ' ') {
9            --endIndex;
10        }
11      
12        // Mark the end position of the last word
13        int startIndex = endIndex;
14      
15        // Move backwards to find the start of the last word
16        while (startIndex >= 0 && s[startIndex] != ' ') {
17            --startIndex;
18        }
19      
20        // Calculate and return the length of the last word
21        // startIndex points to space before word or -1, endIndex points to last char of word
22        return endIndex - startIndex;
23    }
24};
25
1/**
2 * Finds the length of the last word in a string
3 * A word is defined as a maximal substring consisting of non-space characters only
4 * @param s - The input string containing words separated by spaces
5 * @returns The length of the last word in the string
6 */
7function lengthOfLastWord(s: string): number {
8    // Start from the end of the string
9    let endIndex = s.length - 1;
10  
11    // Skip trailing spaces from the end
12    while (endIndex >= 0 && s[endIndex] === ' ') {
13        endIndex--;
14    }
15  
16    // Mark the end position of the last word
17    let startIndex = endIndex;
18  
19    // Move backwards to find the start of the last word
20    while (startIndex >= 0 && s[startIndex] !== ' ') {
21        startIndex--;
22    }
23  
24    // Calculate the length of the last word
25    // startIndex points to the space before the word (or -1 if at beginning)
26    // endIndex points to the last character of the word
27    return endIndex - startIndex;
28}
29

Time and Space Complexity

The time complexity is O(n), where n is the length of the string s. In the worst case, the algorithm needs to traverse the entire string from the end to the beginning. The first while loop skips trailing spaces, and the second while loop counts the characters of the last word. Together, each character is visited at most once, resulting in linear time complexity.

The space complexity is O(1). The algorithm only uses two integer variables i and j to track positions in the string, regardless of the input size. No additional data structures are created that scale with the input, making the space usage constant.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Not handling edge cases with only spaces

A common mistake is not properly handling strings that contain only spaces. If the input is " ", the algorithm might return an incorrect value or fail to handle the case where no word exists.

Problem scenario:

s = "     "  # String with only spaces

After skipping trailing spaces, end_index becomes -1, and if we don't check this condition, accessing s[end_index] in subsequent operations could cause issues.

Solution: Add a check after skipping trailing spaces to handle the case where no word exists:

def lengthOfLastWord(self, s: str) -> int:
    end_index = len(s) - 1
  
    # Skip trailing spaces
    while end_index >= 0 and s[end_index] == ' ':
        end_index -= 1
  
    # Check if the string contains no words (only spaces)
    if end_index < 0:
        return 0
  
    # Continue with finding the word beginning...
    start_index = end_index
    while start_index >= 0 and s[start_index] != ' ':
        start_index -= 1
  
    return end_index - start_index

2. Confusion between pointer positions and actual indices

Developers often get confused about what start_index represents after the second while loop. After finding the beginning of the word, start_index points to either:

  • The space character just before the last word, OR
  • -1 if the last word starts at index 0

Common mistake:

# Incorrect: trying to use start_index + 1 as the beginning
return end_index - (start_index + 1) + 1  # Overcomplicating

Correct understanding: The length calculation end_index - start_index works because:

  • If start_index = -1: length = end_index - (-1) = end_index + 1 (correct for 0-indexed position)
  • If start_index = k (space at position k): length = end_index - k (correct distance)

3. Using built-in methods incorrectly as an alternative

While the two-pointer approach is efficient, some might try to use built-in string methods but implement them incorrectly:

Incorrect approach:

def lengthOfLastWord(self, s: str) -> int:
    return len(s.split()[-1])  # Fails on empty string

Better alternative with built-in methods:

def lengthOfLastWord(self, s: str) -> int:
    words = s.strip().split()
    return len(words[-1]) if words else 0

The manual two-pointer approach is still preferred in interviews as it demonstrates understanding of string manipulation and edge case handling without relying on language-specific features.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

How would you design a stack which has a function min that returns the minimum element in the stack, in addition to push and pop? All push, pop, min should have running time O(1).


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More