58. Length of Last Word - Explanation

Problem Link

Description

You are 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.

Note: A substring is a contiguous non-empty sequence of characters within a string.

Example 1:

Input: s = "Hello World"

Output: 5

Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "

Output: 4

Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"

Output: 6

Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 10,000
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • String Traversal - Iterating through characters in a string from either direction
  • Two-Pointer Technique - Using index variables to track positions while scanning
  • Edge Case Handling - Managing trailing spaces and multiple consecutive spaces in strings

1. Iteration - I

Intuition

We need to find the length of the last word, where words are separated by spaces. Trailing spaces complicate matters since the last word might not be at the very end of the string. By scanning forward, we track the current word's length and reset it when we encounter a new word after spaces.

Algorithm

  1. Initialize length to 0 and start at index 0.
  2. Iterate through the string:
    • If we hit a space, skip all consecutive spaces.
    • If we've reached the end after skipping spaces, return the current length.
    • Otherwise, reset length to 0 (we're starting a new word).
    • For non-space characters, increment length.
  3. Return length after the loop completes.
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        length = i = 0
        while i < len(s):
            if s[i] == ' ':
                while i < len(s) and s[i] == ' ':
                    i += 1
                if i == len(s):
                    return length
                length = 0
            else:
                length += 1
                i += 1
        return length

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

2. Iteration - II

Intuition

Scanning from the end is more direct since we only care about the last word. First skip any trailing spaces, then count characters until we hit a space or the beginning of the string. This avoids processing earlier parts of the string entirely.

Algorithm

  1. Start from the last index of the string.
  2. Skip all trailing spaces by decrementing the index.
  3. Count non-space characters by decrementing the index and incrementing length until a space is found or we reach the start.
  4. Return length.
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i, length = len(s) - 1, 0
        while s[i] == ' ':
            i -= 1
        while i >= 0 and s[i] != ' ':
            i -= 1
            length += 1
        return length

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

3. Built-In Function

Intuition

Most languages provide string manipulation functions that handle splitting and trimming. By splitting the string on spaces and taking the last non-empty segment, we get the last word directly. This trades some efficiency for code simplicity and readability.

Algorithm

  1. Trim trailing spaces from the string (or use split which handles this).
  2. Split the string by spaces.
  3. Return the length of the last element in the resulting array.
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split().pop())

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Common Pitfalls

Not Handling Trailing Spaces

Strings like "Hello World " have trailing spaces after the last word. If you simply scan from the end without first skipping spaces, you will count zero characters. Always skip trailing spaces before counting the last word's length.

Assuming Single Spaces Between Words

The input can have multiple consecutive spaces between words or at the beginning and end. Code that assumes exactly one space between words may produce incorrect results or fail on edge cases like " fly me to the moon ".