Length Of Last Word

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).

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

Contents

Solution using trace the last word from right side and return its length

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.

  • We will create a function traceFromRightSide that takes input argument string s.
  • Base case is, if the length of s is greater than length of t, then we can simply return false.
  • Declare a variable length = 0 to store length of last word.
  • Then, start tracing from right end of the input string s and start incrementing length value, when we find a non space character until a next space is found and exit the program.
  • Finally, return length, which holds the length of last word.
Java
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