Return the length of the last word in a string

Quick Overview

Given a string of English letters and spaces, return the length of its last word, where spaces can appear before, between and after the words. The problem tests careful string scanning, handling of leading and trailing spaces, and a constant-space solution.

Return the length of the last word in a string

Company: IBM

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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. ### Function Signature ```python def length_of_last_word(s: str) -> int: ``` ### Rules - Spaces may appear at the start of `s`, between words (possibly several in a row), and after the last word. - Trailing spaces are not part of any word. ### Constraints - `1 <= len(s) <= 10^4` - `s` consists of only English letters and spaces `' '`. - There is at least one word in `s`. ### Examples ```text Input: s = "Hello World" Output: 5 ``` The last word is "World", which has 5 letters. ```text Input: s = " fly me to the moon " Output: 4 ``` The last word is "moon" with length 4. The two trailing spaces after it are ignored.

Overview: Given a string of English letters and spaces, return the length of its last word, where spaces can appear before, between and after the words. The problem tests careful string scanning, handling of leading and trailing spaces, and a constant-space solution.

IBM logo
IBM
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.

Function Signature

def length_of_last_word(s: str) -> int:

Rules

  • Spaces may appear at the start of s , between words (possibly several in a row), and after the last word.
  • Trailing spaces are not part of any word.

Constraints

  • 1 <= len(s) <= 10^4
  • s consists of only English letters and spaces ' ' .
  • There is at least one word in s .

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

The last word is "moon" with length 4. The two trailing spaces after it are ignored.