SDE & MLE Prep

58. Length of Last Word

Problem

Return the length of the last word in s, where words are maximal runs of non-space characters. s may have leading, trailing or repeated spaces.

Example: " fly me to the moon " → 4

Scan from the end: skip trailing spaces, then count characters until the next space. No split, O(1) extra space.

Complexity: O(n).

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while i >= 0 and s[i] == " ":
            i -= 1
        j = i
        while j >= 0 and s[j] != " ":
            j -= 1
        return i - j