We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Length of Last Word

Number: 58

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Meta, Microsoft, Bloomberg, Apple, Adobe, Yahoo, Uber


Problem Description

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.


Key Insights

  • Remove any trailing spaces to handle edge cases.
  • Find the last space in the string to isolate the last word.
  • The length of the last word is the difference between the total string length (after trimming) and the position of the last space.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string (single pass to trim and another pass to count last word characters). Space Complexity: O(1), using constant extra space.


Solution

We first trim the string to remove trailing spaces which may cause incorrect identification of the last word. Then, we locate the last space character in the trimmed string. The length of the last word is calculated as the difference between the total string length and the index of the last space minus one. This approach uses basic string operations and requires constant space while processing the string in linear time.


Code Solutions

# Function to compute the length of the last word in a string
def length_of_last_word(s):
    # Remove trailing spaces from the string
    s = s.rstrip()
    # Find the index of the last space in the string
    last_space_index = s.rfind(' ')
    # The length of the last word is the total length minus the position of last space - 1
    return len(s) - last_space_index - 1

# Test example
print(length_of_last_word("Hello World"))  # Expected output: 5
← Back to All Questions