Given a string s consisting of words and spaces, return the length of the last word in the string.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Input: s = "Hello World"
Output: 5
Explanation: the last word in input string is "World" with length 5.
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Contents

In this approach, we are going to start from right end of the string and find where the last word starts (without any spaces) and calculate its length.

public class LengthOfLastWord { static int traceFromRightSide(String s) { int length = 0; for(int i=s.length() -1; i>=0 ; i--) { if(s.charAt(i) != ' '){ length++; } if(s.charAt(i) == ' ' && length != 0) { return length; } } return length; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the input string s length.
Space complexity: O(1) since we are using just length variable.

Above implementations source code can be found at GitHub link for Java code