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
- Right-to-Left Thinking: When answer is at the end, start from the end
- Two-Phase Pattern: Separate "skip" phase from "process" phase for clarity
- Bounds Checking: Always check
i >= 0before array access - Space Optimization: Avoid creating arrays/lists when not needed
- 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!"
Related Patterns
- Reverse Words in a String (LC 151)
- Valid Palindrome (LC 125)
- Reverse String (LC 344)
Happy practicing! π―