AlgoMaster Logo

Length of Last Word

easyFrequency4 min readUpdated June 23, 2026

Understanding the Problem

We need the length of the last word in a string. The complication is trailing spaces. "Hello World " has the last word "World" (length 5), so the trailing spaces must be skipped before counting.

The task reduces to: skip any trailing spaces, then count characters backward until reaching another space or the beginning of the string. That count is the answer.

Key Constraints:

  • 1 <= s.length <= 10^4 → A single linear pass is more than fast enough, and the problem has clean O(n) solutions.
  • s consists of only English letters and spaces → No tabs or newlines to handle, so the only delimiter is a single space character.
  • There is at least one word in s → A valid answer always exists, so there is no empty-input case to guard against.

Approach 1: Split and Find Last Word

Intuition

Split the string into words and take the last one. Its length is the answer.

The detail that matters is how the split treats spaces. A naive split(" ") produces empty strings wherever two spaces sit next to each other or at the ends. The fix is to use a whitespace-aware splitter that collapses runs of spaces and drops the empty pieces (Python's str.split() with no argument, Go's strings.Fields), or to filter the empty strings out after splitting on a single space. Either way, the result is a clean list of words, and the last element is the last word.

Algorithm

  1. Split s on whitespace, collapsing runs of spaces so no empty strings remain.
  2. Take the last element of the resulting list.
  3. Return its length.

Example Walkthrough

Input:

0
1
2
3
f
4
l
5
y
6
7
m
8
e
9
10
11
12
t
13
o
14
15
16
17
t
18
h
19
e
20
21
m
22
o
23
o
24
n
25
26
s

After splitting: words = ["fly", "me", "to", "the", "moon"]

Last word is "moon", length = 4:

4
result

Code

This is correct, but it scans the whole string and allocates a list of every word to use only the last one. The next approach removes both costs by working backward from the end.

Approach 2: Traverse from End (Optimal)

Intuition

The last word sits at the end of the string, so scan backward from the last index. First decrement past any trailing spaces. Then count non-space characters until reaching a space or the start of the string. That count is the answer.

This reads only as many characters as needed. For "Hello World", it touches the last 5 characters plus any trailing spaces and never looks at the rest. It also uses no extra storage, so the space cost drops to O(1).

Algorithm

  1. Start from the last index of the string.
  2. Skip all trailing spaces by decrementing the index while the current character is a space.
  3. Count non-space characters by decrementing the index while the current character is not a space.
  4. Return the count.

Example Walkthrough

1Start from the end: i=26
0
1
2
3
f
4
l
5
y
6
7
m
8
e
9
10
11
12
t
13
o
14
15
16
17
t
18
h
19
e
20
21
m
22
o
23
o
24
n
25
26
i
1/6

Code