InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Length of Last Word

easy Original ↗ 00:00

Problem

Given a string s made of letters and spaces, return the length of its last word. A word is a maximal run of non-space characters. The string is guaranteed to contain at least one word, but it may begin or end with any number of spaces, and words may be separated by multiple spaces.

Examples

  • Input: s = "Hello World" → Output: 5 The last word is "World", which has 5 letters.
  • Input: s = " fly me to the moon " → Output: 4 Trailing spaces are ignored; the last word is "moon".
  • Input: s = "luffy is still joyboy" → Output: 6 The last word is "joyboy".

Constraints

  • 1 <= len(s) <= 10^4
  • s consists only of English letters and spaces ' '
  • At least one word is present

Linear time is expected. A common follow-up is doing it in O(1) extra space.

Think about it first

Hint 1 What does Python's `split()` (with no arguments) do with leading, trailing, and repeated spaces?
Hint 2 To avoid building any new strings at all, which end of the string should you start reading from?
Hint 3 Scan from the right: first skip trailing spaces, then count characters until you hit a space or the start of the string. That count is the answer.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug