LeetCode #58 Easy

Length of Last Word

Length of Last Word is LeetCode 58 (Easy). Given a string s of English letters and spaces, return the length of the last word in it.

  • A word is a run of non-space characters, with no space inside it.
  • s may start or end with spaces, and words may be separated by several spaces.
  • At least one word is guaranteed.
Constraints
  • 1 <= s.length <= 10⁴
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.
string
Open on LeetCode ↗
02

Intuition

The last word sits at the end of the string, so read the string from the right. Two things can be there: spaces after the last word, and then the word itself.

  • Skip: move left past every trailing space. You now stand on the last letter of the last word.
  • Count: keep moving left and counting until you meet a space or pass the front of the string.

That count is the answer. Everything before that space is never read, so the scan touches only the last word and the spaces after it, and it needs no extra memory.

How to spot this pattern

When a question only cares about the end of a string or array, start there and walk backwards. You stop as soon as you have the answer instead of tracking everything that came before it.

03

Approach

Try it first

Before reading on, decide where to start reading and what to do with spaces at the very end. Then decide what tells you the last word has started. Aim for O(n) time and O(1) space.

1

Start at the last index

Set i = len(s) - 1. Reading from the right reaches the last word first, so there is no need to remember any earlier word.

2

Skip the trailing spaces

While s[i] is a space, step left. Because the string holds at least one word, this loop always stops on a letter: the last letter of the last word.

3

Count the letters of the word

While i >= 0 and s[i] is a letter, add 1 to length and step left. The first space you meet, or the front of the string, marks where the last word begins, and length is the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lengthOfLastWord(self, s: str) -> int:
▶3 i = len(s) - 1
▶4 while i >= 0 and s[i] == " ":
▶5 i -= 1
▶6 length = 0
▶7 while i >= 0 and s[i] != " ":
▶8 length += 1
▶9 i -= 1
▶10 return length
stringH0e1l2l3o4␣5W6o7r8l9d10ilength0start at the last cell, index 10
i10letter d
length0
The last word is at the end of the string, so the scan starts at index 10 and moves left. Nothing before the last word will ever need to be read.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength0'd' at 10 → the last word ends here
i10letter d
length0
Index 10 is a letter, so the skip loop stops. This is the last letter of the last word; counting starts here.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength1count 'd' → length 1
i10letter d
length1
'd' is part of the last word, so the length grows to 1. Then i moves one cell left to look at the next character.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength2count 'l' → length 2
i9letter l
length2
'l' is part of the last word, so the length grows to 2. Then i moves one cell left to look at the next character.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength3count 'r' → length 3
i8letter r
length3
'r' is part of the last word, so the length grows to 3. Then i moves one cell left to look at the next character.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength4count 'o' → length 4
i7letter o
length4
'o' is part of the last word, so the length grows to 4. Then i moves one cell left to look at the next character.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength5count 'W' → length 5
i6letter W
length5
'W' is part of the last word, so the length grows to 5. Then i moves one cell left to look at the next character.
stringH0e1l2l3o4␣5W6o7r8l9d10ilength5space at 5 → return 5
i5a space
length5
Index 5 is a space, so the last word started just after it. Its length is 5, and the 5 characters before it were never read.
05

Split into words

Splitting on any run of whitespace drops empty pieces, so the last item is always the last word, even when the string ends in spaces. It reads the whole string and stores every word, which is why it uses O(n) space.

▶1class Solution:
▶2 def lengthOfLastWord(self, s: str) -> int:
▶3 return len(s.split()[-1])
06

Common pitfalls

Splitting on a single space

✗ Wrong
return len(s.split(" ")[-1])
✓ Right
return len(s.split()[-1])

split(" ") keeps an empty piece for every extra space, so a string that ends in a space ends with "". On "fly me " it returns 0 instead of 2.

Counting from the left and resetting on spaces

✗ Wrong
length = 0
for ch in s:
    length = 0 if ch == " " else length + 1
return length
✓ Right
length = 0
for i, ch in enumerate(s):
    if ch != " ":
        length = length + 1 if i > 0 and s[i - 1] != " " else 1
return length

The trailing spaces reset the counter after the last word has been measured. On "Hello World " the left-to-right count ends at 0 instead of 5. Reset only when a new word starts.

Dropping the i >= 0 check while counting

✗ Wrong
while s[i] != " ":
✓ Right
while i >= 0 and s[i] != " ":

When the last word starts at index 0, as in "joyboy", i reaches -1. Java and C++ then read outside the string, and Python's s[-1] quietly wraps to the last letter and keeps counting until it crashes.

07

Complexity

Time
O(n)
Space
O(1)
n is the length of s. In the worst case, one long word or a long run of trailing spaces, every character is read once. Only two integers are stored.
08

Length of Last Word FAQ

Can the answer ever be 0?

Not here, because at least one word is guaranteed. If you reuse the code on a string that is all spaces, the skip loop runs past the front, the counting loop never starts, and it returns 0, which is the natural answer for "no words".