Length of Last Word
EasyPrompt
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 <= 104sconsists of only English letters and spaces' '.- There will be at least one word in
s.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach leverages built-in string manipulation functions. First, we remove any leading and trailing whitespace from the string using trim(). Then, we split the string by spaces to get an array of all the words. The last word is simply the last element in this array, and we return its length.
Algorithm
- Call
trim()on the input stringsto remove leading and trailing whitespace. - Call
split(" +")on the trimmed string to get an array of words. The regex" +"handles multiple spaces between words. - Access the last element of the resulting array, which corresponds to the last word.
- Return the length of this last word.
Walkthrough
The core idea is to break down the problem into smaller, manageable steps using standard library functions.
- Trim Whitespace: The input string might have leading or trailing spaces (e.g.,
" hello world "). Thes.trim()method is called to produce a new string"hello world"without these extra spaces. This ensures that when we split the string, we don't get empty strings in our resulting array from trailing spaces. - Split into Words: The trimmed string is then split into an array of words. We use
s.split(" +")where the argument" +"is a regular expression that matches one or more spaces. This correctly handles cases with multiple spaces between words (e.g.,"fly me to the moon"). - Get Last Word: The resulting array contains all the words in order. The last word is at the last index of the array (
words.length - 1). - Calculate Length: Finally, we get the length of this last word and return it.
public class Solution { public int lengthOfLastWord(String s) { // Trim the trailing and leading spaces String trimmedString = s.trim(); // Split the string by one or more spaces String[] words = trimmedString.split(" +"); // The last word is the last element in the array String lastWord = words[words.length - 1]; // Return the length of the last word return lastWord.length(); }}Complexity
Time
O(N)
Space
O(N)
Trade-offs
Pros
Very concise and easy to read, as it relies on high-level built-in functions.
The logic is straightforward and directly maps to the problem's definition.
Cons
Less efficient in terms of memory. It creates a new trimmed string and an array to store all the words, leading to O(N) space complexity.
The overhead of regular expression matching and creating multiple string objects can make it slower than manual iteration for large strings.
A more optimal approach is to iterate through the string from right to left. We can find the length of the last word in a single pass without creating any new data structures. The idea is to first skip any trailing spaces to find the end of the last word. Then, we count the characters of the last word until we encounter a space or the beginning of the string.
Algorithm
- Initialize a pointer
ito the last index of the strings. - Move the pointer
ito the left, skipping all trailing spaces. - Initialize a
lengthcounter to 0. - Once a non-space character is found, start counting. Iterate backwards and increment
lengthfor each non-space character. - Stop when a space is encountered or the beginning of the string is reached.
- Return the final
length.
Walkthrough
This method avoids the overhead of creating intermediate strings and arrays, making it very efficient in terms of space.
- Initialization: We start with a
lengthcounter initialized to 0 and a pointeriset to the last index of the string (s.length() - 1). - Skip Trailing Spaces: We first loop backwards from the end of the string to skip any trailing spaces. The loop
while (i >= 0 && s.charAt(i) == ' ')continues as long as we are within the string bounds and the character is a space. After this loop,iwill point to the last character of the last word. - Count Word Length: Now, we start another backward loop. This loop
while (i >= 0 && s.charAt(i) != ' ')continues as long as we are within the string bounds and the character is not a space. Inside this loop, we increment ourlengthcounter and decrementi. - Return Length: Once this second loop finishes (either by hitting a space or the beginning of the string), the
lengthvariable will hold the length of the last word. We then return this value.
public class Solution { public int lengthOfLastWord(String s) { int length = 0; int i = s.length() - 1; // 1. Skip trailing spaces while (i >= 0 && s.charAt(i) == ' ') { i--; } // 2. Count the length of the last word while (i >= 0 && s.charAt(i) != ' ') { length++; i--; } return length; }}Complexity
Time
O(N)
Space
O(1)
Trade-offs
Pros
Extremely memory efficient with O(1) space complexity, as it doesn't create any new data structures.
Very fast in practice. It performs a single pass from the end and might not even scan the entire string if the last word is near the end.
Cons
The code is slightly more complex to write and reason about compared to the
split()method.
Solutions
Solution
public class Solution { public int LengthOfLastWord(string s) { int i = s.Length - 1; while (i >= 0 && s[i] == ' ') { --i; } int j = i; while (j >= 0 && s[j] != ' ') { --j; } return i - j; }}class Solution {public int lengthOfLastWord(String s) { int i = s.length() - 1; while (i >= 0 && s.charAt(i) == ' ') { --i; } int j = i; while (j >= 0 && s.charAt(j) != ' ') { --j; } return i - j; }}/** * @param {string} s * @return {number} */ var lengthOfLastWord = function ( s,) { let i = s.length - 1; while (i >= 0 && s[i] === " ") { --i; } let j = i; while (j >= 0 && s[j] !== " ") { --j; } return i - j;};class Solution {public: int lengthOfLastWord(string s) { int i = s.size() - 1; while (~i && s[i] == ' ') { --i; } int j = i; while (~j && s[j] != ' ') { --j; } return i - j; }};class Solution: def lengthOfLastWord(self, s: str) -> int: i = len(s) - 1 while i >= 0 and s[i] == ' ': i -= 1 j = i while j >= 0 and s[j] != ' ': j -= 1 return i - jVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.