Length Of Last Word

Find how many letters the last word of a sentence has, even when spaces follow it.

Given a string s made of words and spaces, return the length of its last word. A word is a run of characters that are not spaces. Spaces may appear before, between and after the words, sometimes several in a row, and the string has at least one word.

Example 1
Input: s = "Hello World"
Output: 5
Explanation: the last word is "World", which has 5 letters.
Example 2
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: the last word is "moon"; the two spaces after it do not count.
Example 3
Input: s = "luffy is still joyboy"
Output: 6
Solution

The Idea

When you read a sentence, you find the last word without effort: your eye jumps to the end and picks out the final group of letters. In Example 1, that is "World", and its length is 5.

Example 2 is less tidy. The string "   fly me   to   the moon  " starts with three spaces, has three spaces between some words, and ends with two spaces after "moon". So the very last character is a space, not a letter. Where does the last word begin and end, then?

It ends at the last character that is not a space, and it begins just after the space before that. Everything in front of that space has no effect on the answer. So there is no need to read the string from the start at all. Look at the picture below, where each dot is a space and the small numbers are the positions, or indexes, starting from 0.

The string of Example 2 read from the end. Step 1 skips the spaces at indexes 26 and 25. Step 2 counts n, o, o, m, so length is 4. Step 3 stops at the space at index 20. Indexes 0 to 19 are never read.

Reading starts at index 26, on the right. The label "1. skip spaces at 26 and 25" marks the two spaces at the end of the string, called trailing spaces. They are passed over without counting. Next, "2. count n, o, o, m" counts the letters of "moon" from right to left, which gives 4. Then "3. stop at the space at index 20": a space means the word is over, so the answer is 4.

The grey part, marked "never read", holds most of the string. So the last word can be found by walking backwards in two phases: first past the spaces, then through the letters.

Solution Approach

Turning that idea into code means settling three things: whether Java's built-in string methods are good enough, how to walk past the trailing spaces, and when to stop counting.

Splitting the string into words

Could Java's string methods do the work? s.trim() removes the spaces at both ends, and split(" ") cuts the rest into an array of pieces. The last piece is the last word. This gives the right answer, but it reads every character and builds a new string for every word, only to look at one of them.

Skipping the trailing spaces

How do we get from the end of the string to the last letter? Keep an index i that starts at the last position, s.length() - 1. While the character at i is a space, move i one place to the left. When this stops, i is on the last letter of the last word, which is index 24, the "n" of "moon", in Example 2.

Counting the letters

When does the counting stop? Keep moving i to the left, adding one to a counter for each character, as long as that character is not a space. Counting stops at the first space, like the one at index 20, or when i falls off the start of the string at -1.

That second way to stop matters when the last word is also the first, as in "a". There is no space in front of it, so without the check on i, the loop would ask for the character at index -1, and charAt throws a StringIndexOutOfBoundsException.

Java Solution

The method lengthOfLastWord works in these steps:

  1. First, set the index i to the last position of the string, s.length() - 1.
  2. A first loop moves i left while it is still inside the string (i >= 0) and the character at i is a space. This passes over the trailing spaces.
  3. Then start a counter, length, at 0. A second loop moves i left while it is inside the string and the character is not a space, adding 1 to length each time.
  4. When the second loop stops, return length, the number of letters it passed.

Both loops test i >= 0 before calling s.charAt(i). Java checks the left side of && first, so charAt is never called with -1.

The main method runs the three examples, then a single one-letter word, a word followed by spaces, and a string of only spaces.

Java
public class LengthOfLastWord {

    public static int lengthOfLastWord(String s) {
        int i = s.length() - 1;
        while (i >= 0 && s.charAt(i) == ' ') {
            i--;                              // skip trailing spaces
        }
        int length = 0;
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;                         // count the last word's letters
            i--;
        }
        return length;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLastWord("Hello World"));
        System.out.println(lengthOfLastWord("   fly me   to   the moon  "));
        System.out.println(lengthOfLastWord("luffy is still joyboy"));
        System.out.println(lengthOfLastWord("a"));               // one word, no spaces
        System.out.println(lengthOfLastWord("day   "));          // one word, then spaces
        System.out.println(lengthOfLastWord("   "));             // only spaces
    }
}

Running it prints:

Output
5
4
6
1
3
0

The 5, 4 and 6 at the top match the three examples. Look at the 4: the two spaces after "moon" were skipped, not counted. The 1 comes from "a", where the second loop ends because i reaches -1, not because it meets a space.

The 3 comes from "day   ", and it shows why the first loop is needed. Without it, counting would start on a space and stop at once. A test version without the first loop returns 0 for "Hello World " instead of 5. The last line, 0, is for a string of only spaces. The problem promises at least one word, but the method still returns a sensible answer without one.

The original implementation, LengthOfLastWord.java, is on GitHub.

Complexity

The work is the two backward loops, and together they read each character at most once.

  • Time: O(n) at worst, for a string of n characters. The loops only read the trailing spaces, the last word and the one space before it. That is all n characters only when the string is a single word or nearly all trailing spaces.
  • Space: O(1), because the method keeps only the index i and the counter length. The trim and split way needs O(n) extra space for the array of words.

Walking over words from the end of a string also comes up in Reverse Words in a String.