LeetCode 58 - Length of Last Word

The problem gives us a string s that contains English letters and spaces. Inside this string, words are separated by spaces, and there may also be extra spaces at the beginning or end of the string. Our task is to return the length of the last word in the string.

LeetCode Problem 58

Difficulty: 🟢 Easy
Topics: String

Solution

LeetCode 58, Length of Last Word

Problem Understanding

The problem gives us a string s that contains English letters and spaces. Inside this string, words are separated by spaces, and there may also be extra spaces at the beginning or end of the string.

Our task is to return the length of the last word in the string.

A word is defined as a maximal sequence of non-space characters. In simpler terms, a word is a continuous block of letters with no spaces inside it.

For example:

  • "Hello World" contains two words: "Hello" and "World". The last word is "World", so the answer is 5.
  • " fly me to the moon " contains extra spaces at the beginning, between words, and at the end. The last word is still "moon", so the answer is 4.

The constraints are small:

  • 1 <= s.length <= 10^4
  • The string contains only English letters and spaces.
  • The input is guaranteed to contain at least one word.

These constraints tell us that performance is not extremely critical, but we should still aim for a clean linear-time solution.

Several edge cases are important:

  • Trailing spaces after the last word
  • Multiple spaces between words
  • A string containing only one word
  • A very short string, such as "a"
  • A string where the final word has length 1

A naive implementation can easily fail if it assumes the last character is always part of the last word. For example, "hello " ends with spaces, not letters.

Approaches

Brute Force Approach

A straightforward solution is to split the string into words using spaces.

For example:

s.split()

This automatically removes extra spaces and returns only valid words.

For the input:

"   fly me   to   the moon  "

the result becomes:

["fly", "me", "to", "the", "moon"]

Then we simply take the last word and return its length.

This approach is correct because splitting isolates every valid word in order. The final element in the resulting array is the last word in the string.

The downside is that split() creates an additional list containing all words. Even though the constraints are small, this uses unnecessary extra memory.

Optimal Approach

A more efficient solution scans the string from right to left.

The key observation is that we only care about the final word. We do not need to process or store all words in the string.

The algorithm works in two phases:

  1. Skip all trailing spaces from the end of the string.
  2. Count characters until we encounter another space or reach the beginning.

This avoids creating extra arrays or substrings.

Because every character is visited at most once, the solution runs in linear time with constant extra space.

Approach Comparison

Approach Time Complexity Space Complexity Notes
Brute Force O(n) O(n) Uses split() to store all words
Optimal O(n) O(1) Scans backward without extra storage

Algorithm Walkthrough

  1. Start from the last index of the string.

We initialize a pointer at len(s) - 1 because the last word must appear near the end of the string. 2. Skip trailing spaces.

While the current character is a space, move the pointer left. This handles inputs such as "hello " where spaces appear after the last word. 3. Count characters in the last word.

Once we reach a letter, begin counting characters. Continue moving left until we either:

  • reach the beginning of the string, or
  • encounter a space
  1. Return the count.

The counter now contains the exact length of the final word.

Why it works

The algorithm maintains a simple invariant:

  • After skipping trailing spaces, the pointer always points to the final character of the last word.
  • While counting, every visited character belongs to the last word.
  • The loop stops exactly when the word ends.

Because the algorithm never skips letters inside the final word and stops immediately after the word boundary, the resulting count is guaranteed to be correct.

Python Solution

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        index = len(s) - 1

        # Skip trailing spaces
        while index >= 0 and s[index] == ' ':
            index -= 1

        length = 0

        # Count characters in the last word
        while index >= 0 and s[index] != ' ':
            length += 1
            index -= 1

        return length

The implementation begins by placing index at the final position of the string.

The first while loop removes trailing spaces by moving left until a non-space character is found. This guarantees that the pointer lands on the last character of the final word.

The variable length stores the size of the last word. The second loop continues moving left while characters are not spaces, increasing the counter for each character encountered.

Once a space or the beginning of the string is reached, the full word has been counted, so the function returns length.

Go Solution

func lengthOfLastWord(s string) int {
    index := len(s) - 1

    // Skip trailing spaces
    for index >= 0 && s[index] == ' ' {
        index--
    }

    length := 0

    // Count characters in the last word
    for index >= 0 && s[index] != ' ' {
        length++
        index--
    }

    return length
}

The Go implementation follows the same logic as the Python version.

Strings in Go can be indexed directly using s[index], which returns a byte. Since the problem guarantees only English letters and spaces, byte indexing is completely safe here.

No special handling for empty strings is needed because the constraints guarantee at least one word exists.

Worked Examples

Example 1

Input:

s = "Hello World"

Initial state:

Variable Value
index 10
s[index] 'd'
length 0

There are no trailing spaces, so counting begins immediately.

Step Character Action length index
1 'd' count 1 9
2 'l' count 2 8
3 'r' count 3 7
4 'o' count 4 6
5 'W' count 5 5

At index 5, the character is a space, so the loop stops.

Answer:

5

Example 2

Input:

s = "   fly me   to   the moon  "

The algorithm first skips trailing spaces.

Step Character Action index
1 ' ' skip 28
2 ' ' skip 27

Now the pointer reaches 'n' in "moon".

Counting phase:

Step Character Action length index
1 'n' count 1 26
2 'o' count 2 25
3 'o' count 3 24
4 'm' count 4 23

The next character is a space, so counting stops.

Answer:

4

Example 3

Input:

s = "luffy is still joyboy"

The pointer starts at 'y'.

Step Character Action length index
1 'y' count 1 21
2 'o' count 2 20
3 'b' count 3 19
4 'y' count 4 18
5 'o' count 5 17
6 'j' count 6 16

The next character is a space, so the loop stops.

Answer:

6

Complexity Analysis

Measure Complexity Explanation
Time O(n) In the worst case, every character is visited once
Space O(1) Only a few variables are used

The algorithm performs a single backward scan through the string. Even though there are two loops, each character is processed at most once, so the total runtime remains linear.

The solution uses constant extra memory because no additional arrays, stacks, or substrings are created.

Test Cases

solution = Solution()

assert solution.lengthOfLastWord("Hello World") == 5  # basic two-word case
assert solution.lengthOfLastWord("   fly me   to   the moon  ") == 4  # trailing spaces
assert solution.lengthOfLastWord("luffy is still joyboy") == 6  # longer final word

assert solution.lengthOfLastWord("a") == 1  # single-character word
assert solution.lengthOfLastWord("day") == 3  # single word
assert solution.lengthOfLastWord("hello ") == 5  # one trailing space
assert solution.lengthOfLastWord("hello     ") == 5  # multiple trailing spaces

assert solution.lengthOfLastWord("a b c") == 1  # final word length 1
assert solution.lengthOfLastWord(" abc") == 3  # leading spaces
assert solution.lengthOfLastWord("abc def ghi") == 3  # multiple equal-length words

assert solution.lengthOfLastWord("x y zzzz") == 4  # longer final word
assert solution.lengthOfLastWord("     test") == 4  # many leading spaces
assert solution.lengthOfLastWord("test      word") == 4  # multiple spaces between words

Test Case Summary

Test Why
"Hello World" Standard example with two words
" fly me to the moon " Handles extra spaces everywhere
"luffy is still joyboy" Longer last word
"a" Minimum valid input
"day" Single-word input
"hello " One trailing space
"hello " Multiple trailing spaces
"a b c" Last word has length 1
" abc" Leading spaces before word
"abc def ghi" Multiple words with equal lengths
"x y zzzz" Longer final word
" test" Many leading spaces
"test word" Multiple spaces between words

Edge Cases

Trailing Spaces After the Last Word

Inputs such as:

"hello   "

can break naive implementations that immediately start counting from the final character. The final character is a space, not part of the last word.

The implementation handles this correctly with the first loop, which skips all trailing spaces before counting begins.

Single Word Without Spaces

Inputs such as:

"leetcode"

contain only one word. Some implementations incorrectly assume there will always be a separating space before the last word.

This solution safely continues counting until the index becomes negative, which correctly returns the entire string length.

Multiple Consecutive Spaces Between Words

Inputs such as:

"one     two"

contain several spaces between words.

A poorly written parser may accidentally count spaces or stop incorrectly. This implementation only counts non-space characters during the second loop, so internal spacing does not affect correctness.