Skip to content
← All posts

Length of Last Word: Scanning from the Right

4 min read
leetcodeproblemeasystrings

LeetCode 58, Length of Last Word, gives you a string s consisting of words and spaces. Your job is to return the length of the last word. A word is a maximal substring consisting of non-space characters.

For example:

  • "Hello World" returns 5 (the last word is "World")
  • " fly me to the moon " returns 4 (the last word is "moon")
  • "luffy is still joyboy" returns 6 (the last word is "joyboy")
012345678910111213···fly·me···to···the·moon··last word "moon" (length 4)trailing spaces
The string " fly me to the moon " with the last word highlighted in green and trailing spaces in yellow.

The approach: scan from the right

The last word sits at the end of the string, so start there. The trick is that the string might have trailing spaces. You need to skip past them before you start counting.

The algorithm has two phases:

  1. Skip trailing spaces. Start at the last index and move left while the character is a space.
  2. Count non-space characters. Once you land on a non-space character, keep moving left and counting until you hit a space or reach the beginning of the string.

The count you accumulate in phase two is your answer.

This approach works because you only need the last word. There is no reason to parse the entire string from left to right. Scanning backwards lets you find the answer without processing anything before the last word.

Python's str.rstrip() and str.split() can solve this in one line, but the backwards scan is the technique interviewers want to see. It generalizes to problems where you cannot use built-in string utilities.

The code

def length_of_last_word(s: str) -> int:
    i = len(s) - 1
    while i >= 0 and s[i] == " ":
        i -= 1
    length = 0
    while i >= 0 and s[i] != " ":
        length += 1
        i -= 1
    return length

Walk through what happens:

  1. Set i to the last index of the string.
  2. The first while loop moves i left past any trailing spaces.
  3. Once i points to a non-space character (or has gone below 0), the second while loop counts characters until it hits a space or falls off the left end.
  4. Return length.

Visual walkthrough

Here is the algorithm running on " fly me to the moon ".

Step 1: Start at the end

length = 0
···fly·me···to···the·moon··

Begin at index 26 (the last character). It is a space, so skip it.

Step 2: Skip trailing space

length = 0
···fly·me···to···the·moon··

Index 25 is also a space. Keep moving left.

Step 3: Found a letter

length = 1
···fly·me···to···the·moon··

Index 24 is 'n'. Start counting. Length = 1.

Step 4: Continue counting

length = 2
···fly·me···to···the·moon··

Index 23 is 'o'. Length = 2.

Step 5: Continue counting

length = 3
···fly·me···to···the·moon··

Index 22 is 'o'. Length = 3.

Step 6: Continue counting

length = 4
···fly·me···to···the·moon··

Index 21 is 'm'. Length = 4.

Step 7: Hit a space, stop

length = 4
···fly·me···to···the·moon··

Index 20 is a space. The last word is complete. Return 4.

The pointer starts at index 26, skips two trailing spaces, then counts four characters (n, o, o, m) before hitting a space at index 20. The answer is 4.

Complexity analysis

MetricValue
TimeO(n), where n is the length of the string
SpaceO(1), only a pointer and a counter

In the worst case (no trailing spaces, single word), you scan the entire string. In the best case (the last word is short with few trailing spaces), you touch only a handful of characters. Either way, you never allocate extra memory beyond two integer variables.

Building blocks

This problem uses two techniques that show up across many string and array problems.

Reverse scanning

Instead of reading from left to right, you start at the end and move backward. This is the natural approach any time the answer sits near the end of the input. You will see reverse scanning in problems like reversing a string in place, finding the last occurrence of a character, and trimming suffixes.

Trailing space handling

Strings in real-world inputs often have leading or trailing whitespace. The pattern of skipping past it before doing the real work comes up in string parsing problems like atoi (string to integer), trimming inputs, and tokenizing sentences. The key idea is always the same: consume the noise first, then process the signal.

Edge cases

Trailing spaces. The string "hello " has three trailing spaces. The first loop skips them, then the second loop counts "hello" and returns 5.

Single word. The string "hello" has no spaces at all. The first loop does nothing (the last character is not a space). The second loop counts all five characters.

Single character. The string "a" has length 1. The first loop finds a non-space immediately. The second loop counts 1 character and returns 1.

All spaces. While the problem guarantees at least one word exists, if you were to handle the degenerate case of " ", the first loop would move i past all characters. The second loop would never execute, and the function would return 0.

From understanding to recall

You can follow this solution step by step and feel confident you understand it. But two weeks from now, when you sit down for a coding screen, will you remember to handle trailing spaces before counting? Will the two-loop structure come to you automatically?

Spaced repetition bridges that gap. Instead of re-reading the full solution, you drill the individual building blocks (reverse scan, trailing space skip, counting loop) at increasing intervals. After a few reps spread across days, the pattern is locked in long-term memory. When you see a string manipulation problem in an interview, the pieces are already there.

Related posts