Length of Last Word – Solution & Complexity

1. Understand What Counts as a Word

  • A word is any maximal run of non-space characters.
  • Leading, trailing, and repeated spaces should not count as part of a word.
  • If the string contains only spaces, the answer is 0.

2. Simple Split-Based Idea

  • One straightforward approach is to split the string on whitespace.
  • The last token is the last word, and its length is the answer.
  • This is easy to read, but it creates a list of all words.
def length_of_last_word(s):
    words = s.split()
    if not words:
        return 0
    return len(words[-1])

3. Scan from the End

  • The last word is closest to the end of the string.
  • First skip trailing spaces.
  • Then count characters until you reach another space or the beginning of the string.
i = len(s) - 1
while i >= 0 and s[i] == " ":
    i -= 1

4. Count the Last Word Characters

  • After trailing spaces are skipped, i points at the last character of the last word.
  • Move left while characters are not spaces, increasing a counter.
  • If there was no word, the counter stays at 0.
length = 0
while i >= 0 and s[i] != " ":
    length += 1
    i -= 1

5. Complete Solution and Complexity

  • The final solution uses the end scan to avoid storing extra words.
  • Time complexity is O(n) in the worst case.
  • Space complexity is O(1).
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

FAQ

See also: