Length of Last Word

Easy · Arrays & Hashing · Explanation and code example

Built-In Function

How it works

Most languages provide string manipulation functions that handle splitting and trimming. By splitting the string on spaces and taking the last non-empty segment, we get the last word directly. This trades some efficiency for code simplicity and readability.

Steps

  1. Trim trailing spaces from the string (or use split which handles this).
  2. Split the string by spaces.
  3. Return the length of the last element in the resulting array.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(n)

Things to watch for

Not Handling Trailing Spaces

Strings like "Hello World " have trailing spaces after the last word. If you simply scan from the end without first skipping spaces, you will count zero characters. Always skip trailing spaces before counting the last word's length.

Assuming Single Spaces Between Words

The input can have multiple consecutive spaces between words or at the beginning and end. Code that assumes exactly one space between words may produce incorrect results or fail on edge cases like " fly me to the moon ".

Python code example

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split().pop())

C++ code example

class Solution {
public:
    int lengthOfLastWord(string s) {
        s.erase(s.find_last_not_of(' ') + 1);
        return s.substr(s.find_last_of(' ') + 1).length();
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations