Length of Last Word

EasyStringsstring scan

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s that consists of words separated by one or more space characters, and may also contain leading or trailing spaces. A **word** is a maximal run of consecutive non-space characters. Return the length of the **last** word in s, where the last word is the final maximal run of non-space characters when reading the string from left to right. The input is guaranteed to contain at least one word, so the answer is always a positive integer.

Examples

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

Constraints

  • `1 <= s.length <= 10^4`
  • `s` consists of only English letters and space characters `' '`.
  • `s` contains at least one non-space character (at least one word).

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.