Length of Last Word in Java (LeetCode 58): Strings

At first glance, LeetCode 58 (Length of Last Word) looks like it needs a full split() call, an array of tokens, and some bounds-checking. It doesn't. Because you only care about the word at the very end of the string, you can walk backward from the last index and stop the moment you hit a space after counting letters. No splitting, no extra array, just one backward pass.

In this post I'll break down why scanning from the back works, dry-run it against a few tricky inputs (trailing spaces included), and then share clean Java for it. There's also a small interactive walker below so you can step through the backward scan character by character.

Video Walkthrough

Prefer to watch it instead? Here's the full walkthrough, from reading the problem to submitting the solution:


1. What the Problem Asks

You're given a string s made of letters and spaces. A "word" is a maximal run of non-space characters. The task is to return the length of the last word in the string — not the first, not the longest, just the one closest to the end.

Rules & Observations:
  • The string can have leading or trailing spaces, and there can be more than one space between words.
  • There is guaranteed to be at least one word somewhere in the string, so you never have to handle a completely empty result.
  • You don't need to know anything about the words before the last one — their lengths, their positions, none of it matters.

The Core Idea: Scan From the End

Instead of splitting the whole sentence into pieces, start at the last index of the string and move left. First, skip over any trailing spaces until you land on an actual letter. Then keep counting letters until you either hit a space or run off the front of the string. That count is your answer, and you never had to look at anything before the last word.

Scanning "Hello World " From the Back
Trailing spaces
skip, don't count ignored
'd', 'l', 'r'...
letters of "World" count++
space before 'W'
boundary found stop here

By the time we hit that boundary space, count already holds the length of "World", which is 5.

Quick Examples

Input: s = "Hello World"
Output: 5
Why: The last word is "World", which has 5 letters.
Input: s = " fly me to the moon "
Output: 4
Why: Ignoring the trailing spaces, the last word is "moon".
Input: s = "luffy is still joyboy"
Output: 6
Why: The last word is "joyboy".

2. Interactive Backward Scanner

Step through the scan below, right to left, and watch the counter build up until it hits a boundary space.

Length of Last Word Simulator
Watch the pointer walk backward from the end of the string.
Presets:
Sentence:
Click "Step back" to start scanning from the end.

3. Step-by-Step Code Walkthrough

Here's the logic behind the Java solution, broken into plain steps:

  1. Trim the string first: Calling s.trim() removes any leading or trailing spaces up front, so the loop doesn't need separate logic just to skip them at the very end of the string.
  2. Walk backward: Start a pointer i at s.length() - 1 and move it toward index 0.
  3. Count or stop: At each position, if the character isn't a space, increment a counter. The moment a space is hit, break out immediately — that space marks the start boundary of the last word.
  4. Return the counter: Once the loop ends, whatever the counter holds is the length of the last word.

The Java Solution

class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim();
        int c = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                c++;
            } else {
                break;
            }
        }
        return c;
    }
}

Test It Locally

Use this Main class to run a handful of edge cases, including multiple inner spaces and trailing whitespace:

public class Main {
    public static int lengthOfLastWord(String s) {
        s = s.trim();
        int c = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                c++;
            } else {
                break;
            }
        }
        return c;
    }

    public static void main(String[] args) {
        String[] testCases = {
            "Hello World",
            "   fly me   to   the moon  ",
            "luffy is still joyboy",
            "a"
        };

        for (String test : testCases) {
            System.out.println("\"" + test + "\" -> " + lengthOfLastWord(test));
        }
    }
}

Console Output:

"Hello World" -> 5
" fly me to the moon " -> 4
"luffy is still joyboy" -> 6
"a" -> 1

4. Complexity Analysis

  • Time Complexity: O(n) in the worst case, where n is the length of the string. In practice we often stop far earlier, as soon as the boundary space before the last word is found.
  • Space Complexity: O(1) for the scanning logic itself. The call to trim() does allocate a new string internally, so if you want strictly constant extra space, you can skip trim() and instead manually skip trailing spaces before starting the count — the loop logic barely changes.

5. Traps & Interview Tips

  • Don't forget trailing spaces: A naive backward loop that starts counting immediately, without first skipping trailing spaces, will return 0 for an input like "hello ". Either call trim() first, or add a separate skip phase before you start counting.
  • Forward scan is messier: You could solve this by splitting on spaces and taking the last non-empty token, but that means allocating an array and handling repeated spaces carefully. Scanning backward avoids all of that extra bookkeeping.
  • Watch the loop exit condition: The loop has two ways to end — hitting a space (break) or running past index 0 (the for-loop condition i >= 0 failing). Both cases correctly leave c holding the right answer, so there's no special-casing needed for a string with only one word.
  • Related problems to practice:
    • LeetCode 151 (Reverse Words in a String): Builds on the same idea of scanning for word boundaries around spaces.
    • LeetCode 28 (Find the Index of the First Occurrence in a String): Another pointer-walking problem that rewards avoiding unnecessary allocations.

Comments

Popular posts from this blog

Climbing Stairs in Java (LeetCode 70): DP Approach

Unique Paths in Java (LeetCode 62): DP Approach

Longest Valid Parentheses in Java (LeetCode 32): Stack Approach