AlgoInsight

DSA problem

Length of Last Word

EasyStringsPattern: String Traversaltop600AmazonMicrosoftGoogle

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only. The string may contain leading, trailing, or multiple consecutive spaces, so you cannot assume the last character is part of a word.

For example, in the string " fly me to the moon " the last word is "moon", whose length is 4. It is guaranteed that there is at least one word in s.

Examples

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

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringtraversal

Browse all DSA problems