InterviewPrepKit

Home / Coding / Arrays & Hashing

Length of Last Word

easy Original β†—
Solving tips
  • Recognize the answer lives entirely at the right end, so scan backwards rather than parsing the whole string.
  • From the last index, first skip trailing spaces, then count non-space characters until you hit a space or the start; O(n) time, O(1) space.
  • The one-liner len(s.split()[-1]) works but allocates every word β€” mention the O(1)-space reverse scan for the follow-up.
  • Pitfall: forgetting the trailing-space skip returns 0, and always check i >= 0 before indexing s[i].

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; the interesting 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.