Popular interviews 150
String manipulation is a common coding interview topic, and this question is a great example of handling substrings effectively. let us solve it LeetCode 58: Length of the last word Use simple methods.
🚀 Problem description
Given a string s
It consists of single words and spaces and returns the length of the last word in the string.
- A word is defined as the largest substring consisting only of non-space characters.
💡 Example
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.
🏆 JavaScript solution
This problem can be solved by trimming unnecessary spaces and effectively positioning the last word.
implement
var lengthOfLastWord = function(s) {
const words = s.trim().split(' ');
return words[words.length - 1].length;
};
🔍 How it works
- Trim string:
- Remove leading and trailing spaces using
trim()
to simplify the logic.
- Remove leading and trailing spaces using
- Split string:
- use
split(' ')
Divide the string into single words based on spaces.
- use
- Get the last sentence:
- Access the last element of the array (
words[words.length - 1
]) and return its length.
- Access the last element of the array (
🔑 Complexity analysis
- > Time complexity:
O(n)
is the length of the string. Both trimming and splitting strings run in linear time. - > Space complexity:
O(n)
because splitting creates an array of single words.
Alternative solution (without splitting)
For space efficiency, traverse the string backwards to find the last word:
var lengthOfLastWord = function(s) {
let length = 0;
let i = s.length - 1;
// Skip trailing spaces
while (i >= 0 && s[i] === ' ') {
i--;
}
// Count characters of the last word
while (i >= 0 && s[i] !== ' ') {
length++;
i--;
}
return length;
};
🔑 Complexity analysis (alternative solutions)
- > Time complexity:
O(n)
when we iterate through the string once. - > Space complexity:
O(1)
because no additional data structures are used.
📋 Run on empty
enter: s = "fly me to the moon"
Output: 4
✨ Professional tips for interviews
-
Explicit restrictions:
- Can the string be empty?
- Are there multiple spaces between words?
-
Optimize for edge cases:
- Enter only spaces (
" "
→0
). - Single word input (
"hello"
→5
).
- Enter only spaces (
📚 Learn more
Check out the full explanation and code walkthrough on my Dev.to post:
👉 length of last word – JavaScript solution
How would you solve this problem? Let’s discuss it! 🚀