Length of Last Word

Easy

Topics
String

Given a string s of words and spaces, return the length of the last word. A word is a maximal substring of non-space characters.

Example 1

Hello World
last word
The answer is 5. The catch is trailing spaces: scanning from the right, those have to be skipped before the word is measured, which is why a naive split on a single space can give the wrong answer.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "Hello World"
Output: 5

Example 2

fly me to the moon
last word
Input:  s = "   fly me   to   the moon  "
Output: 4

Example 3

luffy is still joyboy
last word
Input:  s = "luffy is still joyboy"
Output: 6

Constraints

  • 1 <= s.length <= 10^4
  • s consists of English letters and spaces, with at least one word.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Splitting on whitespace and taking the last token is the one-liner, and it is fine. It does allocate a list of every word to use only the final one, which is O(n) space for an O(1)-space problem.

Scanning from the right costs nothing extra: skip any trailing spaces, then count characters until the next space or the start of the string. The work stops as soon as the last word is measured, so it touches only the tail rather than the whole input.

Approach

  1. Walk back from the end while the character is a space.
  2. Then count back while the character is not a space.

Dry Run

s = "Hello World   "

skip trailing spaces:  i moves 13 -> 10, landing on 'd'
count the word:        d,l,r,o,W  -> length 5, i stops on the space at 5

answer 5

s = "a"      no trailing spaces, count 'a'  -> 1
s = "   fly me   there  "
             skip two trailing spaces, count "there" -> 5

Complexity

  • Time — O(n) worst case, and in practice only the trailing segment is examined — a long string ending in a short word costs almost nothing. Splitting scans the whole string unconditionally.
  • Space — O(1): two integers. This is the real reason to prefer it: split() allocates every word, so it is O(n) space to answer a question about one of them.

Common Pitfalls

  • Forgetting trailing spaces. "Hello World " must give 5; counting from the last character immediately gives 0.
  • Taking split()[-1] without checking for an empty result. The constraints guarantee at least one word here, so it is safe — but only because of that guarantee.
  • Counting from the first space found from the left, which measures the first word.
  • Treating other whitespace as a separator. The input contains only letters and spaces by constraint.

Full Solution — all languages

class Solution:
    def lengthOfLastWord(self, s):
        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
SensAI
Beta
Tap the mic to stop voice mode