DSA Guide
Strings

Length of Last Word

Measure the final word by scanning backwards, skipping trailing spaces first

EasyReverse Scan
String
Problem #58

Problem Statement

Given a string s consisting of words separated by spaces, return the length of the last word. A word is a maximal run of non-space characters.

Input:  "Hello World"
Output: 5

Input:  "   fly me   to   the moon  "
Output: 4      ("moon")

Input:  "luffy is still joyboy"
Output: 6      ("joyboy")

Intuition

The one-liner is tempting: split on spaces, take the last piece, return its length. It works — but it builds a list of every word when you only need one, and it has to handle the empty strings that trailing spaces produce.

The key insight

The last word is at the end, so start there.

  1. Walk backwards past any trailing spaces.
  2. Then count non-space characters until you hit a space or the start of the string.

You touch only the trailing spaces plus the last word — never the rest of the string.

The two phases must be separate. Trying to count and skip in one loop is what produces the classic bug on inputs like "hello ", where a naive scan reports 0.

Watch it run

"the moon " — two phases, right to left
t
h
e
m
o
o
n
i
phaseskip spaceslength0
Start at the last index. It is a space → skip it.
1 / 5
Two distinct phases: skip, then count.

Approach

Phase 1 — skip trailing spaces

Decrement while the current character is a space.

Phase 2 — count the word

Decrement while the current character is not a space, incrementing a counter.

Solution

def length_of_last_word(s: str) -> int:
    """Length of the final word in s."""
    i = len(s) - 1

    # Phase 1: skip trailing spaces.
    while i >= 0 and s[i] == " ":
        i -= 1

    # Phase 2: count the word's characters.
    length = 0
    while i >= 0 and s[i] != " ":
        length += 1
        i -= 1

    return length

The built-in version, which is perfectly acceptable and very readable:

def length_of_last_word_split(s: str) -> int:
    words = s.split()      # split() with no argument drops empty pieces
    return len(words[-1]) if words else 0

A split trap in JavaScript

"a b ".split(' ') returns ["a", "b", "", ""] — the trailing spaces produce empty strings, so words[words.length - 1] is "" and the answer would be 0.

Python's "a b ".split() (no argument) collapses whitespace and drops empties, returning ["a", "b"]. The two languages behave differently here, which is why the TypeScript version needs .trim() and a regex.

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

  • Time — worst case O(n) when the string is one long word or mostly trailing spaces. Typically far less, since only the tail is examined.
  • Space — two integers. The split versions allocate O(n) for the word list, which is the practical reason to prefer the backwards scan.

Edge Cases

On this page