ExamAdda Logo

Length of Last Word

Easy

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

A word is defined as a maximal substring consisting of non-space characters only.

Example 1

Input

Hello World

Output

5

Explanation

The last word is "World", which contains 5 characters.

Example 2

Input

fly me   to   the moon

Output

4

Explanation

Trailing spaces are ignored. The last word is "moon", which has a length of 4.

Constraints

1 ≤ s.length ≤ 10⁴
s consists of English letters and spaces.
There is at least one word in s.

Hints:

Hint 1

Ignore any trailing spaces before processing the last word.

Hint 2

Traverse the string from the end. Count characters until you encounter a space after counting has started.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Published

Sep 29, 2026

Last updated

Sep 29, 2026

Last technically reviewed

Sep 29, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output