Code Logo

Length of Last Word

Published at25 Jul 2026
Medium 5 views
Like0

Given a string s consisting of words separated by single spaces, return the length of the last word. A word is defined as a maximal substring of non-space characters.

For example, the last word of "Hello World" has length 5 (World). The last word of "fly me to the moon" has length 4 (moon). The last word of "luffy is still joyboy" has length 6 (joyboy). An empty string returns 0. A single-word string like "Hello" returns 5.

Finding the length of the last word is a classic string problem that tests your ability to parse text efficiently from the end. Instead of splitting the entire string into an array of words (which wastes memory), you can traverse from the rightmost character, skip any trailing spaces, and count until you encounter a space or reach the beginning of the string.

The optimal approach works in one pass from right to left. First, advance past any trailing spaces. Then count consecutive non-space characters until a space or the start of the string is reached. This approach avoids allocating intermediate arrays and uses only a constant amount of extra memory.

Edge cases include an empty string (return 0), a string containing only spaces (return 0, since there are no words), a single word with no spaces (return its length), and a string with multiple trailing spaces (the algorithm must skip them before counting).

Example Input & Output

Example 1
Input
"a "
Output
1
Explanation

Last word 'a' has 1

Example 2
Input
"hello"
Output
5
Explanation

Single word

Example 3
Input
""
Output
0
Explanation

Empty string

Example 4
Input
" fly me to the moon "
Output
4
Explanation

Last word 'moon' has 4

Example 5
Input
"Hello World"
Output
5
Explanation

Last word 'World' has 5 letters

Algorithm Flow

Recommendation Algorithm Flow for Length of Last Word

Solution Approach

Given a string s consisting of words and spaces, return the length of the last word. Traverse from the end of the string backward, skipping trailing spaces. Once a non-space character is found, start counting until another space or the beginning of the string. This avoids splitting the entire string and uses O(1) extra space.

function lengthOfLastWord(s) {
  var i = s.length - 1, count = 0;
  while (i >= 0 && s[i] === ' ') i--;
  while (i >= 0 && s[i] !== ' ') { count++; i--; }
  return count;
}

Two backward loops: first skips trailing spaces, then counts consecutive non-space characters. This handles cases with multiple trailing spaces correctly without needing to trim or split the input.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(String s) {
        s=s.trim();return s.length()-s.lastIndexOf(' ')-1;
    }
}