algoadvance

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.

Clarifying Questions

  1. Input Format:
    • Is the string guaranteed to contain at least one word?
      • Yes, at least one word is present in the string.
  2. Whitespace Handling:
    • How should leading or trailing whitespaces be handled?
      • Leading and trailing whitespaces should be ignored. Only the length of the last word should be considered.
  3. Character Set:
    • Can the string contain any special characters or should it only contain alphabetic characters?
      • The problem specifies words and spaces, so let’s assume it can include other non-space characters too.
  4. Output:
    • What should be returned if there are no non-space characters in the input string?
      • This scenario does not occur based on the guarantee of at least one word in the string.

Strategy

  1. Trimming Whitespace:
    • First, we will strip the trailing whitespace from the string to ensure trailing spaces are not considered.
  2. Splitting the String:
    • We can then split the trimmed string into words based on spaces.
    • The last element in this list of words will be our last word.
  3. Calculating the Length:
    • Simply return the length of the last word in the list.

Code

Here is the implementation in Python:

def lengthOfLastWord(s: str) -> int:
    # Strip the trailing whitespace if any
    s = s.rstrip()
    
    # Split the string based on spaces
    words = s.split(' ')
    
    # The last word will be the last element in the split list
    last_word = words[-1]
    
    # Return the length of the last word
    return len(last_word)

Time Complexity

Thus, the overall time complexity of the function is O(n), where n is the length of the input string s.

Try our interview co-pilot at AlgoAdvance.com