Length of Last Word
Easy
Topics
Given a string s of words and spaces, return the length of the last word. A word is a maximal substring of non-space characters.
Example 1
last word
The answer is 5. The catch is trailing spaces: scanning from the right, those have to be skipped before the word is measured, which is why a naive split on a single space can give the wrong answer.
Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "Hello World" Output: 5
Example 2
last word
Input: s = " fly me to the moon " Output: 4
Example 3
last word
Input: s = "luffy is still joyboy" Output: 6
Constraints
- 1 <= s.length <= 10^4
- s consists of English letters and spaces, with at least one word.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Splitting on whitespace and taking the last token is the one-liner, and it is fine. It does allocate a list of every word to use only the final one, which is O(n) space for an O(1)-space problem.
Scanning from the right costs nothing extra: skip any trailing spaces, then count characters until the next space or the start of the string. The work stops as soon as the last word is measured, so it touches only the tail rather than the whole input.
Approach
- Walk back from the end while the character is a space.
- Then count back while the character is not a space.
Dry Run
s = "Hello World "
skip trailing spaces: i moves 13 -> 10, landing on 'd'
count the word: d,l,r,o,W -> length 5, i stops on the space at 5
answer 5
s = "a" no trailing spaces, count 'a' -> 1
s = " fly me there "
skip two trailing spaces, count "there" -> 5Complexity
- Time — O(n) worst case, and in practice only the trailing segment is examined — a long string ending in a short word costs almost nothing. Splitting scans the whole string unconditionally.
- Space — O(1): two integers. This is the real reason to prefer it:
split()allocates every word, so it is O(n) space to answer a question about one of them.
Common Pitfalls
- Forgetting trailing spaces.
"Hello World "must give 5; counting from the last character immediately gives 0. - Taking
split()[-1]without checking for an empty result. The constraints guarantee at least one word here, so it is safe — but only because of that guarantee. - Counting from the first space found from the left, which measures the first word.
- Treating other whitespace as a separator. The input contains only letters and spaces by constraint.
Full Solution — all languages
class Solution:
def lengthOfLastWord(self, s):
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return lengthimport java.util.*;
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') i--;
int length = 0;
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int lengthOfLastWord(string s) {
int i = (int)s.size() - 1;
while (i >= 0 && s[i] == ' ') i--;
int length = 0;
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};/**
* @param {string} s
* @return {number}
*/ var lengthOfLastWord = function(s) {
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') i--;
let length = 0;
while (i >= 0 && s[i] !== ' ') {
length++;
i--;
}
return length;
};