Talentd
FleetCode
Make and follow sheets.Sign in

Length of Last Word solution and explanation

EasyString5 min read59.7% acceptanceUpdated 9 Apr 2026
Length of Last Word | LeetCode problem 58 | Top 150 interview question seriesTechnosage · 4:15 · 85K viewsWatch on YouTube
9 more videos on this problem
  1. Length of Last Word | LeetCode problem 58 | Top 150 interview question seriesTechnosage · 4:15 · 85K views
  2. Length of Last Word - Leetcode 58 - PythonNeetCode · 6:26 · 54K views
  3. Length of Last Word (LeetCode 58) | Full solution with examples | Easiest MethodNikhil Lohia · 10:48 · 14K views
  4. LeetCode 58: Length of Last Word | Beginner's Coding InterviewAbstracted Away · 3:37 · 11K views
  5. Leetcode | 58. Length of Last Word | Easy | Java SolutionDeveloper Docs · 2:53 · 8K views
  6. Length of Last Word - LeetCode #58 - 3 solutions - Python, JavaScript, Java, C++CodingNinja · 8:24 · 5K views
  7. Spotify Coding Interview Question - LeetCode 58 - Length of Last WordAlgoJS · 6:12 · 4K views
  8. Length of Last Word | LeetCode 58 | Coding Interview TutorialTerrible Whiteboard · 8:57 · 3K views
  9. Length of Last Word | LeetCode 58 | Programming TutorialsProgramming Tutorials · 6:22 · 3K views
  10. How To Solve "58. Length of Last Word" on LeetCode - JavaScript EasyBecoming A Better Dev (with David) · 7:09 · 1K views

The problem

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

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Approach overview

Problem Overview: You receive a string that may contain words separated by spaces, including trailing spaces at the end. The task is to return the length of the last word. A word is defined as a sequence of non-space characters. The challenge is mainly handling trailing spaces efficiently.

Approach 1: Split and Trim Approach (O(n) time, O(n) space)

The most straightforward strategy is to clean the string and split it into words. First remove leading and trailing spaces using trim() or equivalent. Then split the string using a space delimiter and access the final element of the resulting array. The length of that last element is the answer. This works because splitting converts the sentence into a list of individual words, making the last word easy to access.

This approach is easy to implement and readable in interviews, especially in languages with built-in string utilities. The tradeoff is extra memory usage because the split operation allocates an array of substrings. Time complexity is O(n) since the string is scanned to trim and split, and space complexity is O(n) due to storing all words. The solution mainly relies on operations from the string manipulation toolkit.

Approach 2: Reverse Traversal Approach (O(n) time, O(1) space)

A more efficient method scans the string from the end instead of creating intermediate structures. Start with a pointer at the last index and skip any trailing spaces by moving left while the character is a space. Once the first non-space character is found, begin counting characters until another space or the start of the string appears. The counter value represents the length of the last word.

This technique avoids splitting or allocating extra arrays. It performs a single linear scan and maintains only a few variables. Time complexity remains O(n), but space complexity drops to O(1) because no additional data structures are created. Conceptually, it behaves like a backward pointer scan similar to patterns used in two pointers problems, while still focusing on string traversal.

Recommended for interviews: Interviewers typically expect the reverse traversal approach. The split-based method demonstrates basic string manipulation and quickly produces a working solution, but it uses extra memory and hides the underlying logic. The reverse scan shows that you understand how to iterate through a string carefully, handle trailing spaces, and compute the answer in constant space. Starting with the simple approach and then optimizing to the reverse traversal method demonstrates both correctness and algorithmic awareness.

Approach 1: Split and Trim Approach

This approach involves trimming any trailing spaces from the string, splitting it into words using spaces as delimiters, and then simply returning the length of the last word in the resulting list of words.

def length_of_last_word(s: str) -> int:
    return len(s.strip().split()[-1])

print(length_of_last_word("Hello World"))  # Outputs 5
class Solution {
    public int lengthOfLastWord(String s) {
        String[] words = s.trim().split(" ");
        return words[words.length - 1].length();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.lengthOfLastWord("Hello World")); // Outputs 5
    }
}
#include <iostream>
#include <sstream>
using namespace std;

int lengthOfLastWord(string s) {
    istringstream ss(s);
    string word;
    while (ss >> word) {}
    return word.size();
}

int main() {
    string str = "Hello World";
    cout << lengthOfLastWord(str) << endl; // Outputs 5
    return 0;
}
function lengthOfLastWord(s) {
    let words = s.trim().split(' ');
    return words[words.length - 1].length;
}

console.log(lengthOfLastWord("Hello World"));  // Outputs 5
#include <stdio.h>
#include <string.h>

int lengthOfLastWord(char * s) {
    int length = 0;
    for (int i = strlen(s) - 1; i >= 0; i--) {
        if (s[i] == ' ' && length > 0) {
            break;
        }
        if (s[i] != ' ') {
            length++;
        }
    }
    return length;
}

int main() {
    char str[] = "Hello World";
    printf("%d\n", lengthOfLastWord(str)); // Outputs 5
    return 0;
}
using System;

class Solution {
    public int LengthOfLastWord(string s) {
        string[] words = s.Trim().Split(' ');
        return words[words.Length - 1].Length;
    }

    static void Main(string[] args) {
        Solution solution = new Solution();
        Console.WriteLine(solution.LengthOfLastWord("Hello World")); // Outputs 5
    }
}

This Python solution trims the input string, splits it into words, and returns the length of the last word found.

Complexity

Time Complexity: O(n)
Space Complexity: O(m)

Try this approach in the editor

Approach 2: Reverse Traversal Approach

This approach involves traversing the string from the end, skipping spaces, and then counting the length of the last word by scanning backward.

def length_of_last_word(s: str) -> int:
    length = 0
    i = len(s) - 1
    while i >= 0 and s[i] == ' ':
        i -= 1
    while i >= 0 and s[i] != ' ':
        length += 1
        i -= 1
    return length

print(length_of_last_word("   fly me   to   the moon  "))  # Outputs 4
class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0, i = s.length() - 1;
        while (i >= 0 && s.charAt(i) == ' ') i--;
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;
            i--;
        }
        return length;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.lengthOfLastWord("   fly me   to   the moon  ")); // Outputs 4
    }
}
#include <iostream>
using namespace std;

int lengthOfLastWord(string s) {
    int length = 0, i = s.length() - 1;
    while (i >= 0 && s[i] == ' ') i--; // Skip trailing spaces
    while (i >= 0 && s[i] != ' ') {
        length++;
        i--;
    }
    return length;
}

int main() {
    string str = "luffy is still joyboy";
    cout << lengthOfLastWord(str) << endl; // Outputs 6
    return 0;
}
function lengthOfLastWord(s) {
    let length = 0;
    let i = s.length - 1;
    while (i >= 0 && s.charAt(i) === ' ') i--;
    while (i >= 0 && s.charAt(i) !== ' ') {
        length++;
        i--;
    }
    return length;
}

console.log(lengthOfLastWord("luffy is still joyboy"));  // Outputs 6
#include <stdio.h>
#include <string.h>

int lengthOfLastWord(char * s) {
    int len = strlen(s);
    int length = 0;
    while (len > 0 && s[len - 1] == ' ') --len; // Skip trailing spaces
    while (len > 0 && s[len - 1] != ' ') {
        length++;
        len--;
    }
    return length;
}

int main() {
    char str[] = "   fly me   to   the moon  ";
    printf("%d\n", lengthOfLastWord(str)); // Outputs 4
    return 0;
}
using System;

class Solution {
    public int LengthOfLastWord(string s) {
        int length = 0, i = s.Length - 1;
        while (i >= 0 && s[i] == ' ') i--;
        while (i >= 0 && s[i] != ' ') {
            length++;
            i--;
        }
        return length;
    }

    static void Main(string[] args) {
        Solution solution = new Solution();
        Console.WriteLine(solution.LengthOfLastWord("   fly me   to   the moon  ")); // Outputs 4
    }
}

The Python method leverages reverse traversal to count and return the last non-space character sequence length.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 3: Reverse Traversal + Two Pointers

We start traversing from the end of the string s, find the first character that is not a space, which is the last character of the last word, and mark the index as i. Then continue to traverse forward, find the first character that is a space, which is the character before the first character of the last word, and mark it as j. Then the length of the last word is i - j.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

function lengthOfLastWord(s: string): number {
    let i = s.length - 1;
    while (i >= 0 && s[i] === ' ') {
        --i;
    }
    let j = i;
    while (j >= 0 && s[j] !== ' ') {
        --j;
    }
    return i - j;
}
func lengthOfLastWord(s string) int {
	i := len(s) - 1
	for i >= 0 && s[i] == ' ' {
		i--
	}
	j := i
	for j >= 0 && s[j] != ' ' {
		j--
	}
	return i - j
}
impl Solution {
    pub fn length_of_last_word(s: String) -> i32 {
        let s = s.trim_end();
        let n = s.len();
        for (i, c) in s.char_indices().rev() {
            if c == ' ' {
                return (n - i - 1) as i32;
            }
        }
        n as i32
    }
}
class Solution {
    /**
     * @param String $s
     * @return Integer
     */
    function lengthOfLastWord($s) {
        $count = 0;
        while ($s[strlen($s) - 1] == ' ') {
            $s = substr($s, 0, -1);
        }
        while (strlen($s) != 0 && $s[strlen($s) - 1] != ' ') {
            $count++;
            $s = substr($s, 0, -1);
        }
        return $count;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Split and Trim Approach

Time Complexity: O(n)
Space Complexity: O(m)

Reverse Traversal Approach

Time Complexity: O(n)
Space Complexity: O(1)

Reverse Traversal + Two Pointers–

Complexity analysis

ApproachTimeSpaceWhen to Use
Split and Trim ApproachO(n)O(n)When quick implementation and readability matter more than memory usage
Reverse Traversal ApproachO(n)O(1)Preferred in interviews and memory-constrained scenarios

Frequently asked questions

Is Length of Last Word easy or hard?

Length of Last Word is classified as an Easy problem on LeetCode with an acceptance rate of around 58%. The challenge mainly involves correctly handling trailing spaces and understanding basic string iteration.

Length of Last Word Python/Java solution

In Python or Java, the problem can be solved using either string splitting or reverse traversal. The split approach uses built-in functions like split() and trim(), while the optimal solution iterates from the end of the string and counts characters until a space appears.

How to solve Length of Last Word in O(n)?

Traverse the string from the end. First skip any trailing spaces, then count characters until a space or the beginning of the string is reached. This single pass guarantees O(n) time while using constant extra space.

What is the best approach for Length of Last Word?

The reverse traversal approach is usually the best solution. It scans the string from the end, skips trailing spaces, and counts characters of the last word. This method runs in O(n) time and O(1) space, making it more memory efficient than splitting the string.

Is Length of Last Word asked at Google/Amazon/Meta?

Length of Last Word appears frequently in coding interview preparation lists and has been reported in interview practice sets for companies like Amazon and Google. It tests basic string manipulation and edge-case handling such as trailing spaces.

What data structure is used in Length of Last Word?

The problem mainly uses string traversal rather than complex data structures. Some solutions temporarily use arrays created by splitting the string, but the optimal approach only relies on simple index pointers while scanning the string.

What is the time complexity of Length of Last Word?

The optimal solution runs in O(n) time where n is the length of the string. In the reverse traversal method, the algorithm scans the string once from right to left. Space complexity is O(1) because it only uses a few variables.

Comments

Now write it yourselfClose this page and solve Length of Last Word in the editor, without looking.
Practise Length of Last Word