Length of Last Word (LeetCode 58): Solution and Explanation

Easy
String

You get a string made of letters and spaces, and you need to return how many characters are in its final word. A word is a maximal run of non-space characters, and the string may have extra spaces at the start, at the end, or between words.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The most obvious approach is to split the string on whitespace and take the length of the last piece. That works, but it builds a list of every word in the string just to look at one of them. The question only cares about the tail of the string, so it is worth thinking about how to answer it by looking only at the end.

If the string had no trailing spaces, the last word would simply be everything after the final space character. Its length would be the total length minus the position of that last space, minus one more for the space itself. If there is no space at all, the whole string is one word, and the same formula still works when the 'last space' is treated as position -1.

The only thing that breaks this idea is trailing whitespace, because then the final space sits after the word instead of before it. Stripping spaces from the right end removes that problem. After the strip, the string is guaranteed to end with a letter, and the last space (if any) marks the boundary just before the last word. That is exactly what the reference code does in two lines: rstrip(), then len(s) - s.rfind(' ') - 1.

Approach: Trim and find the last space

  1. Call s.rstrip() to remove every trailing space, so the string now ends on the last character of the last word.
  2. Call s.rfind(' ') to get the index of the final remaining space, or -1 if the trimmed string contains no space at all.
  3. Everything after that index belongs to the last word, so its length is len(s) - s.rfind(' ') - 1.
  4. Return that value. When rfind returns -1, the expression becomes len(s), which correctly counts a single-word string.

Step-by-step example

s = "fly me   to   the moon  "
  1. The original string ends with two spaces. After rstrip(), it becomes "fly me to the moon", which has length 22.
  2. Scanning from the right, the first space found is the one between "the" and "moon", at index 17, so rfind(' ') returns 17.
  3. The last word occupies indices 18 through 21, which is "moon".
  4. The formula gives 22 - 17 - 1 = 4, and the function returns 4.

Code: Python, Java, C++

1class Solution:
2    def lengthOfLastWord(self, s: str) -> int:
3        s = s.rstrip()
4        return len(s) - s.rfind(' ') - 1

Time and space complexity

Time

O(n)

Both rstrip and rfind scan the string at most once from the right, so the work is linear in the length of s. In practice they stop early, but the worst case (for example a single long word) touches every character.

Space

O(n)

Python strings are immutable, so rstrip returns a new string that can be nearly as long as the input. The backward-scan alternative below avoids this copy and uses O(1) space.

Other approaches

Backward scan with a counter (time O(n), space O(1))

Start an index at the end of the string, step left past any spaces, then step left again while counting non-space characters until you hit a space or fall off the start. It does the same work without allocating a trimmed copy, which makes it the version interviewers usually want when they ask about constant space.

Split on whitespace (time O(n), space O(n))

Use s.split() and return len(words[-1]). It is short and readable, but it allocates a list holding every word in the string, which is wasteful when only the last one matters.

Common mistakes

  • Skipping the trailing-space trim. Without it, rfind(' ') lands on the last character of the string and the formula returns 0 for input like "moon ".
  • Using s.split(' ') with an explicit separator. That produces empty strings for runs of spaces, so the last element can be "" and the answer comes out as 0.
  • In the backward-scan version, counting while you are still inside the trailing spaces. You need two separate loops: one that skips spaces and one that counts letters.
  • Forgetting the single-word case. If your loop only stops on a space, make sure it also stops at index 0 so it does not read past the start of the string.

Frequently asked questions

Can you solve Length of Last Word in O(1) space?

Yes. Walk an index backward from the end, skip trailing spaces, then count characters until you reach a space or the start of the string. No new string or list is created, so extra space is constant.

Why subtract one in len(s) - s.rfind(' ') - 1?

The value from rfind is the index of the space itself, and the word starts one position after it. Subtracting the space index from the length counts the space plus the word, so you remove one to leave only the word's characters.

What happens if the string has only one word?

After trimming there is no space left, so rfind returns -1. The formula becomes len(s) + 1 - 1, which is the full length of the trimmed string, exactly the length of that single word.

Is split() acceptable in an interview?

It gives the right answer and is fine as a first pass, but expect a follow-up asking you to avoid building the full list of words. Showing the backward scan afterward demonstrates that you understand what the library call costs.