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.
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.
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.
Production-Ready Systems with LLMs and Agents
A live Maven cohort, 5 October to 2 November: eight 90-minute sessions where you build LLM and agent systems that survive real traffic, real cost and real failure. Tuesdays and Thursdays, 7:30 to 9:00pm London.
Cohort 2 starts 5 October. Eight live sessions, $1,500.
View the live cohortKeep reading
- The Algorithms Worth Knowing in Code Review: Cutting Big O Without Being Clever
- Tracking Down the Mystery: Finding the Unique Delivery ID
- Elusive Least Occurring Number in an Array
- Solving the Height of a Binary Tree Puzzle
- Harry Potter Discounts: A Code Challenge Algorithm
- Implementing a Task Heap Service in TypeScript