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 provided 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 spaces, and the `split(" ")` method also processes the entire string to create a list of words. The final operation, `len(s[-1])`, takes constant time O(1) since it simply retrieves the length of the last word. The space complexity is O(m), where m is the number of words in the string. This is due to the space required to store the list created by the `split(" ")` method. In the worst case, if the string consists of multiple words, the space used will be proportional to the number of words. However, if the string is empty or consists only of spaces, the space complexity can be considered O(1) since no words would be stored.
remove all hanging spaces, split the string into a list of words then just return the last index’s length