Skip to content

3. Length of Last Word

πŸ”— LeetCode Problem: 58. Length of Last Word
πŸ“Š Difficulty: Easy
🏷️ Topics: String

Problem Statement

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

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word 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

Constraints: - 1 <= s.length <= 10^4 - s consists of only English letters and spaces ' ' - There is at least one word in s


Quick Revision Notes

🎯 Core Concept:

Find the last word by scanning from the right side, skip trailing spaces, then count characters until next space (or start of string).

⚑ Quick Implementation:

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;
}

πŸ”‘ Key Insights:

  • Scan from right to left - most efficient approach
  • Two-phase: Skip trailing spaces, then count word characters
  • No string splitting needed - saves time and space
  • Trailing spaces are common - must handle explicitly

πŸŽͺ Memory Aid:

"Start from the end, skip spaces, count backwards!"
Think: "Right-to-left scan beats left-to-right"


🎨 Visual Understanding

The Problem Visualized

Input: s = "   fly me   to   the moon  "

Character-by-character view:
Index:  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25
Char:  ' ' ' ' ' ' 'f' 'l' 'y' ' ' 'm' 'e' ' ' ' ' 't' 'o' ' ' ' ' 't' 'h' 'e' ' ' 'm' 'o' 'o' 'n' ' ' ' '
                    └─wordβ”€β”˜     β””wordβ”˜         β””wordβ”˜         └─wordβ”€β”€β”˜     └──last wordβ”€β”€β”€β”˜  β””spacesβ”˜

Step 1: Start from end (index 25)
Step 2: Skip trailing spaces (indices 25, 24)
Step 3: Found 'n' at index 23 - start counting
Step 4: Count: 'n', 'o', 'o', 'm' = 4 characters
Step 5: Hit space at index 19 - STOP

Result: 4

Scanning Direction Comparison

❌ Left-to-Right (Inefficient):
   "   fly me   to   the moon  "
    ↓
    Need to track ALL words, remember last one
    Must process entire string even if answer is at end

βœ… Right-to-Left (Optimal):
   "   fly me   to   the moon  "
                              ↑
    Skip spaces, count immediately
    Only process what's needed for answer

Edge Cases Visualization

Case 1: No trailing spaces
"hello world"
           ↑
    Start here, immediately count 'd','l','r','o','w' = 5

Case 2: Only one word
"hello"
     ↑
    Start here, count until beginning = 5

Case 3: Many trailing spaces
"word    "
        ↑
    Skip all spaces first, then count 'd','r','o','w' = 4

Case 4: Single letter word at end
"a b c"
     ↑
    Immediately count 'c' = 1

🎯 Approach 1: Built-in Split Method

The Most Natural Thinking πŸ’­

Core Logic:

1. Split string by spaces β†’ get array of words
2. Take last element from array
3. Return its length

Why this works:
- Java's split() handles multiple spaces automatically
- Last array element is last word
- Simple one-liner logic

Why This Works: - Split naturally separates words - Array indexing gives last word - No manual parsing needed

Drawbacks: - Creates entire array of all words (unnecessary) - Uses O(n) extra space - Processes entire string even for answer at end

Implementation

public int lengthOfLastWord(String s) {
    // Split by spaces, filter empty strings
    String[] words = s.trim().split(" +");

    // Return length of last word
    return words[words.length - 1].length();
}

⏰ Time: O(n) - must process entire string
πŸ’Ύ Space: O(n) - stores array of all words


βœ… Approach 2: Right-to-Left Scanning (Optimal)

The Efficient Strategy πŸ’‘

Core Logic:

Two-phase approach:
Phase 1: Skip trailing spaces (move pointer left)
Phase 2: Count word characters (until space or start)

Why scan right-to-left?
- Last word is at the end β†’ start from end
- Only process what's needed
- No extra data structures
- Early termination possible

Why This is Better: - Space efficient: O(1) - no arrays or splits - Time efficient: Often faster as we start where answer is - Clean logic: Two simple while loops - Handles all edge cases: trailing spaces, single word, etc.

Implementation

public int lengthOfLastWord(String s) {
    int length = 0;
    int i = s.length() - 1;  // Start from rightmost character

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

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

    return length;
}

Step-by-Step Execution: s = " fly me to the moon "

Initial Setup:
═══════════════════════════════════════════════════════════════════
String: "   fly me   to   the moon  "
Length: 26 characters
Start position: i = 25 (last index)
Goal: Find length of "moon" = 4
═══════════════════════════════════════════════════════════════════

Character array with indices:
Index:  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25
Char:  ' ' ' ' ' ' 'f' 'l' 'y' ' ' 'm' 'e' ' ' ' ' 't' 'o' ' ' ' ' 't' 'h' 'e' ' ' 'm' 'o' 'o' 'n' ' ' ' '


πŸ“ PHASE 1: Skip Trailing Spaces
───────────────────────────────────────────────────────────────────

Iteration 1:
  i = 25
  s.charAt(25) = ' ' (space)
  Condition: i >= 0 && s.charAt(i) == ' ' β†’ TRUE
  Action: i-- β†’ i = 24
  Status: Still in trailing spaces

Iteration 2:
  i = 24
  s.charAt(24) = ' ' (space)
  Condition: i >= 0 && s.charAt(i) == ' ' β†’ TRUE
  Action: i-- β†’ i = 23
  Status: Still in trailing spaces

Iteration 3:
  i = 23
  s.charAt(23) = 'n' (not a space!)
  Condition: i >= 0 && s.charAt(i) == ' ' β†’ FALSE
  Action: Exit while loop
  Status: Found start of last word

Result after Phase 1: i = 23, pointing at 'n'


πŸ“ PHASE 2: Count Word Characters
───────────────────────────────────────────────────────────────────

Iteration 1:
  i = 23
  s.charAt(23) = 'n'
  Condition: i >= 0 && s.charAt(i) != ' ' β†’ TRUE
  Action: length++ β†’ length = 1
  Action: i-- β†’ i = 22
  Word so far: "n" (length 1)

Iteration 2:
  i = 22
  s.charAt(22) = 'o'
  Condition: i >= 0 && s.charAt(i) != ' ' β†’ TRUE
  Action: length++ β†’ length = 2
  Action: i-- β†’ i = 21
  Word so far: "on" (length 2)

Iteration 3:
  i = 21
  s.charAt(21) = 'o'
  Condition: i >= 0 && s.charAt(i) != ' ' β†’ TRUE
  Action: length++ β†’ length = 3
  Action: i-- β†’ i = 20
  Word so far: "oon" (length 3)

Iteration 4:
  i = 20
  s.charAt(20) = 'm'
  Condition: i >= 0 && s.charAt(i) != ' ' β†’ TRUE
  Action: length++ β†’ length = 4
  Action: i-- β†’ i = 19
  Word so far: "moon" (length 4)

Iteration 5:
  i = 19
  s.charAt(19) = ' ' (space!)
  Condition: i >= 0 && s.charAt(i) != ' ' β†’ FALSE
  Action: Exit while loop
  Status: Hit space before last word - DONE

Result after Phase 2: length = 4

═══════════════════════════════════════════════════════════════════
🎯 FINAL RESULT: 4
═══════════════════════════════════════════════════════════════════

Visual trace of pointer movement:
Index:  19  20  21  22  23  24  25
Char:  ' ' 'm' 'o' 'o' 'n' ' ' ' '
              4β†’  3β†’  2β†’  1β†’  ↑   ↑
                              skip skip

Started at index 25, skipped 2 spaces, counted 4 characters

Another Example: s = "Hello World"

Initial Setup:
═══════════════════════════════════════════════════════════════════
String: "Hello World"
Length: 11 characters
Start position: i = 10 (last index)
═══════════════════════════════════════════════════════════════════

Index:  0   1   2   3   4   5   6   7   8   9   10
Char:  'H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd'


πŸ“ PHASE 1: Skip Trailing Spaces

Iteration 1:
  i = 10
  s.charAt(10) = 'd' (not a space!)
  Condition: i >= 0 && s.charAt(i) == ' ' β†’ FALSE
  Action: Exit while loop immediately
  Status: No trailing spaces to skip

Result: i = 10


πŸ“ PHASE 2: Count Word Characters

Count 'd': i=10 β†’ length = 1, i = 9
Count 'l': i=9  β†’ length = 2, i = 8
Count 'r': i=8  β†’ length = 3, i = 7
Count 'o': i=7  β†’ length = 4, i = 6
Count 'W': i=6  β†’ length = 5, i = 5
Hit space at i=5 β†’ STOP

═══════════════════════════════════════════════════════════════════
🎯 FINAL RESULT: 5
═══════════════════════════════════════════════════════════════════

⏰ Time: O(n) worst case, but often much faster
πŸ’Ύ Space: O(1) - only two integer variables


πŸ” Edge Cases

Case 1: No trailing spaces
Input: "Hello World"
Output: 5
Strategy: Phase 1 skips nothing, Phase 2 counts normally

Case 2: Multiple trailing spaces
Input: "Hello World    "
Output: 5
Strategy: Phase 1 skips all trailing spaces first

Case 3: Multiple spaces between words
Input: "Hello    World"
Output: 5
Strategy: Doesn't matter - we scan from right

Case 4: Single word only
Input: "Hello"
Output: 5
Strategy: Phase 1 skips nothing, Phase 2 counts until i < 0

Case 5: Single word with spaces
Input: "   Hello   "
Output: 5
Strategy: Phase 1 skips trailing, Phase 2 counts word

Case 6: Single character word
Input: "a b c"
Output: 1
Strategy: Counts just 'c'

Case 7: Leading and trailing spaces
Input: "   a   "
Output: 1
Strategy: Leading spaces don't matter, skip trailing, count 'a'

Case 8: Maximum length string
Input: 10,000 character string ending with word
Output: Length of last word
Strategy: Still O(1) space, scans from end

Common Mistakes

Mistake 1: Not handling trailing spaces
❌ Wrong: Start counting immediately from end
βœ“ Right: Skip trailing spaces FIRST, then count

Example: "word  " β†’ wrong would count 2 (spaces), correct is 4

Mistake 2: Using left-to-right scan
❌ Wrong: Scan entire string, track all words
βœ“ Right: Scan from right, stop when done

Why: Wastes time processing unnecessary characters

Mistake 3: Forgetting index bounds check
❌ Wrong: while (s.charAt(i) == ' ')
βœ“ Right: while (i >= 0 && s.charAt(i) == ' ')

Why: Prevents ArrayIndexOutOfBounds when entire string is one word

Mistake 4: Using split without trim
❌ Wrong: s.split(" ")
βœ“ Right: s.trim().split(" +")

Why: Trailing spaces create empty strings in array

Mistake 5: Counting spaces in length
❌ Wrong: Count until end regardless of character
βœ“ Right: Stop counting when space encountered

Example: Should not include spaces in word length

🎯 Key Takeaways

⚑ Algorithm Comparison

Approach 1: Split Method
  Time: O(n)
  Space: O(n) - stores all words
  Pros: Simple, one-liner
  Cons: Wastes space, processes entire string

Approach 2: Right-to-Left Scan (OPTIMAL)
  Time: O(n) worst case, often faster
  Space: O(1) - two integers only
  Pros: Efficient, handles all cases, minimal memory
  Cons: Slightly more code

Winner: Approach 2 for space efficiency and elegance

πŸ”‘ Pattern Recognition

Problem Type: String Parsing - Last Element
Core Pattern: Reverse scan from end

When to Apply:
βœ“ Need information about last element
βœ“ Want to avoid processing entire input
βœ“ Space optimization important
βœ“ Early termination possible

Key Technique:
β†’ Two-phase scanning (skip unwanted, count wanted)
β†’ Right-to-left traversal
β†’ Character-by-character inspection

Related Problems:
- Reverse Words in a String
- Valid Palindrome (scanning from both ends)
- Remove Duplicates from Sorted Array

🧠 Interview Communication

Step 1: "I notice we need the LAST word, so scanning right-to-left makes sense"
Step 2: "First, I'll skip any trailing spaces"
Step 3: "Then count characters until I hit another space or reach start"
Step 4: "This is O(n) time but O(1) space, better than splitting"
Step 5: "It also terminates early - we don't process the whole string"

πŸ’‘ Pro Tips

  1. Right-to-Left Thinking: When answer is at the end, start from the end
  2. Two-Phase Pattern: Separate "skip" phase from "process" phase for clarity
  3. Bounds Checking: Always check i >= 0 before array access
  4. Space Optimization: Avoid creating arrays/lists when not needed
  5. Edge Case First: Consider trailing spaces before writing code

Final Optimal Code (Recall Friendly)

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

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

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

    return length;
}

Memory Hook: "Skip from end, count backwards, stop at space!"


  • Reverse Words in a String (LC 151)
  • Valid Palindrome (LC 125)
  • Reverse String (LC 344)

Happy practicing! 🎯