Skip to main content

Length of Last Word - Solution & Explanation

EasyString15 min readAsked at: Amazon, Microsoft, Meta +4
Practice this problem

Problem Statement

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.

The C solution trims trailing spaces from the end first by iterating backward, and counts non-space characters to find the length of the last word.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), no extra space is used besides counters.

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.

The C solution navigates from the end of the string, skipping trailing spaces, and counts the length of the word in reverse.

Code

C

C++

Java

Python

C#

JavaScript

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).

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

C#

PHP

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Split and Trim Approach

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), no extra space is used besides counters.

Reverse Traversal Approach

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

Reverse Traversal + Two Pointers—

Detailed 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

Video Solution

Length of Last Word | LeetCode problem 58 | Top 150 interview question series • Technosage • 85,534 views views

Watch 9 more video solutions →

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.

Ready to solve this problem?

Practice Length of Last Word with our built-in code editor and test cases.

Practice on FleetCode