Skip to content
Problem 58 · LeetCode 58(opens in a new tab)

Length of Last Word

EasyStrings

A string s holds English letters and spaces. A word is a run of letters with no space inside it, as long as it can be. There may be spaces before the first word, between words (more than one) and after the last word.

Return how many letters the last word in s has.

Example 1

Input:  s = "cats nap  "
Output: 3
Why:    the last word is "nap"; trailing spaces do not count
2 more examples and the constraints

Example 2

Input:  s = "   blue sky"
Output: 3
Why:    the last word is "sky"

Example 3

Input:  s = "q"
Output: 1
Why:    the whole string is one word

Constraints

  • 1 ≤ s.length ≤ 10,000
  • s has only English letters and the space character
  • s contains at least one word

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split into wordsO(n)
  2. Scan from the endO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCharacters read, long inputVerdict
Split into wordsO(n)
Passes; stores every word
Scan from the endO(n)
Best; reads only the tail

n = length of s. The scan stops at the space before the last word, so for a long sentence it reads only a few characters.

Edge cases to test

  • Trailing spaces. "cats nap " ends in spaces; they must be skipped, not counted as an empty word.
  • One word, no spaces. "reading": the count loop runs off the front, so it needs the i >= 0 check.
  • A single letter. "q" returns 1; "q " also returns 1.
  • Leading spaces. " zebra" returns 5; the spaces in front are never reached.

Common mistakes

  • Returning 0 for a string that ends in a space, because the count starts on the space.
  • Dropping the i >= 0 check, so a string that is one word reads past the front.
  • Splitting on a single space without trimming, which leaves empty strings as the "last word".

How to talk through it

  1. 1Clarify. Only letters and spaces? Can there be several spaces in a row, or spaces at the end? Is there always a word?
  2. 2Give the split answer. Split on spaces and take the last piece. O(n) time, but it stores every word.
  3. 3Notice only the end matters. Read from the back: skip spaces, then count letters.
  4. 4Code the two loops. One loop skips trailing spaces, one counts letters and guards against falling off the front.
  5. 5Test out loud. Try trailing spaces, a single word and a single letter before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?