easy Length of Last Word
Problem Statement
Given a string str which contains words and spaces, return the length of the last word in the str.
A word is defined as a substring containing non-space characters only.
Examples
1.Example 1:
- Input: str =
"Fly to the moon" - Expected Output: 4
- Justification: The last word is "moon" which consists of 4 characters.
- Example 2:
- Input: str =
"Java Programming 101 " - Expected Output: 3
- Justification: The last word is "101" which consists of 3 characters. Note the trailing spaces are ignored.
- Example 3:
- Input: str =
" " - Expected Output: 0
- Justification: There is no word in this string, only spaces.
Try it yourself
Try solving this question here:
✅ Solution Length of Last Word
Problem Statement
Given a string str which contains words and spaces, return the length of the last word in the str.
A word is defined as a substring containing non-space characters only.
Examples
1.Example 1:
- Input: str =
"Fly to the moon" - Expected Output: 4
- Justification: The last word is "moon" which consists of 4 characters.
- Example 2:
- Input: str =
"Java Programming 101 " - Expected Output: 3
- Justification: The last word is "101" which consists of 3 characters. Note the trailing spaces are ignored.
- Example 3:
- Input: str =
" " - Expected Output: 0
- Justification: There is no word in this string, only spaces.
Solution
To solve this problem, we adopt a straightforward yet effective strategy by analyzing the given string from its end towards the beginning. This approach allows us to directly locate and measure the last word, bypassing any preceding content or trailing spaces that do not contribute to the final count.
By employing a simple backward traversal, we efficiently find the end of the last word and then determine its length by counting the characters until a space or the start of the string is encountered.
Step-by-Step Algorithm
-
Initialize Pointer: Set a pointer or index variable to the last position of the input string. This is used to traverse the string from the end towards the beginning.
-
Skip Trailing Spaces: Move the pointer backwards (decrement the pointer) as long as the character at the current pointer position is a space. This step ensures that any trailing spaces are ignored when determining the length of the last word.
-
Initialize Last Word Length Counter: Once trailing spaces are skipped, initialize a variable to count the length of the last word. Set this counter to 0 initially.
-
Count the Length of the Last Word: Continue moving the pointer backwards (decrementing the pointer) and increment the last word length counter for each non-space character encountered. Stop if a space character is encountered, indicating the start of the last word has been reached, or if the beginning of the string is reached.
-
Return Last Word Length: Once the start of the last word is identified or the beginning of the string is reached, return the last word length counter as the length of the last word.
Algorithm Walkthrough
Let's consider the input: str = "Fly to the moon".
-
Initialize Pointer: Set the pointer to position 14 (the last character position in the string "Fly to the moon").
-
Skip Trailing Spaces: There are no trailing spaces in this example, so the pointer remains at position 14 (character 'n').
-
Initialize Last Word Length Counter: Set the last word length counter to 0.
-
Count the Length of the Last Word:
- Pointer at position 14 (character 'n'), increment counter to 1. Move pointer to position 13.
- Pointer at position 13 (character 'o'), increment counter to 2. Move pointer to position 12.
- Pointer at position 12 (character 'o'), increment counter to 3. Move pointer to position 11.
- Pointer at position 11 (character 'm'), increment counter to 4. Move pointer to position 10.
- Pointer at position 10 (character ' '), encounter a space, indicating the start of the last word has been found.
-
Return Last Word Length: The last word length counter is 4, which is the length of the last word "moon". Return 4.
Code
public class Solution {
public int lengthOfLastWord(String str) {
// Initialize a pointer for traversing from the end, removing trailing spaces
int pointer = str.length() - 1;
while (pointer >= 0 && str.charAt(pointer) == ' ') {
pointer--; // Skip trailing spaces
}
// Initialize length counter for the last word
int lastWordLength = 0;
while (pointer >= 0 && str.charAt(pointer) != ' ') {
pointer--; // Move backwards through the last word
lastWordLength++; // Increment length for each character found
}
return lastWordLength; // Return the computed length of the last word
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
String example1 = "Fly to the moon";
System.out.println("Example 1 Input: \"" + example1 + "\"");
System.out.println(
"Expected Output: " + solution.lengthOfLastWord(example1)
); // Expected Output: 4
// Example 2
String example2 = "Java Programming 101 ";
System.out.println("Example 2 Input: \"" + example2 + "\"");
System.out.println(
"Expected Output: " + solution.lengthOfLastWord(example2)
); // Expected Output: 3
// Example 3
String example3 = " ";
System.out.println("Example 3 Input: \"" + example3 + "\"");
System.out.println(
"Expected Output: " + solution.lengthOfLastWord(example3)
); // Expected Output: 0
}
}
Complexity Analysis
Time Complexity:
The time complexity of this algorithm is
Space Complexity:
The space complexity is
🤖 Don't fully get this? Learn it with Claude
Stuck on Length of Last Word? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Length of Last Word** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Length of Last Word** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Length of Last Word**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Length of Last Word**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.