Approach
remove all hanging spaces, split the string into a list of words then just return the last index’s length
Search
Jun 27, 20241 min readThe time complexity of the given solution is O(n), where n is the length of the input string `s`. This is because the `rstrip()` method iterates through the string to remove trailing whitespace, and the `split()` method also processes the entire string to create a list of words. Therefore, both operations contribute to a linear time complexity. The space complexity is O(m), where m is the number of words in the string after splitting. This is due to the storage required for the list created by the `split()` method. In the worst case, if the string contains many words, the space used will be proportional to the number of words. However, if we consider only the last word, the space complexity can be viewed as O(1) if we disregard the space used for the list of words, focusing solely on the length of the last word being returned.
remove all hanging spaces, split the string into a list of words then just return the last index’s length