Length of Last Word
(#58), Easy
Category: String
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.
Examples
Input: s = "Hello World"
Output: 5
Explanation: The last word is 'World', which has 5 characters.
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is 'moon', which has 4 characters.
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is 'joyboy', which has 6 characters.
Approach
Approach: Reverse Traversal
- Initialize an empty string `subStr`.
- Loop from the end of the string to the beginning:
- - If the current character is a space and `subStr` is empty, continue (skip trailing spaces).
- - If the current character is a space and `subStr` is not empty, return `subStr.length` (we found the last word).
- - Otherwise, append the current character to `subStr`.
- After the loop, return `subStr.length` in case the string has only one word.
// 🔹 Manual Reverse Loop Approach
var lengthOfLastWord = function (s) {
let subStr = "";
for (let i = s.length - 1; i >= 0; i--) {
if (s[i] === " " && subStr === "") continue;
else if (s[i] === " " && subStr.length > 0) return subStr.length;
else subStr += s[i];
}
return subStr.length;
};
Approach: Trim and Split
- Use `trim()` to remove trailing and leading spaces.
- Use `split(" ")` to convert the string into words.
- Return the length of the last element in the resulting array.
// 🔹 Built-in Method (Short Code)
var lengthOfLastWord = function (s) {
let words = s.trim().split(" ");
return words[words.length - 1].length;
};
Complexity
Time: O(n) – We scan the string once
Space: O(1) for reverse loop, O(n) for split-based version