Algorithm

Length of Last Word Algorithm

Given a string of words and spaces, return the length of the last word.

8 Apr 2024

Length of Last Word Algorithm

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.

Go further
Live cohort on Maven

AI Transformation for Organisational Leaders

For directors, heads of function and founders: eight live evening sessions with Ehsan Gazar and Anoosh Zeighami, ending with a one-page 2027 AI plan for your organisation, built on a real workflow and ready for your leadership team.

$1,495, or $1,045 with code EARLYBIRD until 23 Oct.

View the live cohort

Keep reading