Learnitweb

Length of Last Word

1. Problem Summary

You are given a string s consisting of upper-case letters, lower-case letters, and spaces.

Your task is to return the length of the last word in the string, where:

  • A word is defined as a sequence of non-space characters.
  • Trailing spaces at the end of the string must be ignored.
  • The last word ends at the last non-space character in the string.

Example interpretation:
For input "Hello World", the last word is "World" and the result is 5.


2. Key Insights

Words are separated by spaces

Multiple spaces can appear between words or at the end.

Last word means:

  • scan from the end backward
  • skip trailing spaces
  • count characters until a space is hit

No need to split the string

Splitting creates extra space and time overhead.

Efficient linear scan from right

You only need one backward traversal.


3. Approach

Reverse traversal counting characters

Steps:

  1. Start from the last index of the string.
  2. Skip all trailing spaces.
  3. Begin counting characters until:
    • you reach a space, or
    • you reach the start of the string.
  4. Return the count.

This method avoids unnecessary string operations and handles all edge cases cleanly.


4. Time and Space Complexity

Time Complexity: O(N)

At worst, the entire string is scanned once.

Space Complexity: O(1)

No extra data structures needed.


5. Java Solution

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        int i = s.length() - 1;

        // Skip trailing spaces
        while (i >= 0 && s.charAt(i) == ' ') {
            i--;
        }

        // Count characters of last word
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;
            i--;
        }

        return length;
    }
}

6. Dry Run Examples

Example 1

Input:

"Hello World"

Step-by-step:

  • Start from last char → ‘d’ (not space)
  • Count: 1, 2, 3, 4, 5
  • Stop at space between Hello and World
  • Final output: 5

Example 2

Input:

"   Fly me   to   the moon  "

Processing:

  • Skip trailing spaces at end
  • Last non-space word starts at “moon”
  • Count characters: m-o-o-n → 4
  • Final output: 4

Example 3

Input:

"a"
  • No spaces
  • Count = 1
  • Final output: 1

Example 4

Input:

"day"
  • Entire string is a word
  • Count = 3
  • Final output: 3

Example 5

Input:

"Today is a nice day   "
  • Skip trailing spaces
  • Count characters in “day” → 3
  • Final output: 3

7. Why This Solution Works

  • Ignores trailing spaces correctly
  • Recognizes word boundaries efficiently
  • Avoids costly split operations
  • Handles single-word cases
  • Works for long strings safely
  • Uses constant memory

8. Common Mistakes

  1. Using split(" ") (fails with multiple spaces)
  2. Counting trailing spaces as part of last word
  3. Forgetting to stop at start of string
  4. Assuming only one space between words
  5. Returning zero on valid single-letter input