Length of Last Word Algorithm
Given a string of words and spaces, return the length of the last word.
8 Apr 2024

Given a string of words and spaces, return the length of the last word.
Input: s = "Hello World"
Output: 5
The last word is "World" with length 5.
The quick way
Trim trailing spaces. Split by spaces. Grab the last element's length. Done.
Javascript
var lengthOfLastWord = function(s) {
const words = s.trim().split(" ");
return words[words.length - 1].length;
};
The efficient way
You don't need to split the entire string. Walk backwards from the end, skip any trailing spaces, then count characters until you hit a space or the beginning.
Javascript
var lengthOfLastWord = function(s) {
let length = 0;
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') i--;
while (i >= 0 && s[i] !== ' ') {
length++;
i--;
}
return length;
};
Complexity
- Time: O(n) for both approaches — worst case you scan the whole string.
- Space: O(n) for the split approach (creates an array), O(1) for the backward scan.
Trade-offs
The split approach is more readable. The backward scan is more efficient on memory. For interview purposes, showing both signals that you understand the tradeoff. In production, readability wins unless the string is massive.