Top Interview 150
String manipulation is a common coding interview topic, and this problem is a great example of working with substrings efficiently. Let’s solve LeetCode 58: Length of Last Word using a straightforward approach.
🚀 Problem Description
Given a string s consisting of words and spaces, return the length of the last word in the string.
- A word is defined as a maximal substring consisting of non-space characters only.
đź’ˇ Examples
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
The problem can be solved by trimming unnecessary spaces and locating the last word efficiently.
Implementation
var lengthOfLastWord = function(s) {
    const words = s.trim().split(' ');
    return words[words.length - 1].length;
};
🔍 How It Works
- Trim the String:
- Remove leading and trailing spaces using trim()to simplify the logic.
 
- Remove leading and trailing spaces using 
- Split the String:
- Use split(' ')to divide the string into words based on spaces.
 
- Use 
- Get the Last Word:
- 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. Trimming and splitting the string both run in linear time.
- > Space Complexity: O(n), as splitting creates an array of words.
Alternative Solution (No Split)
For improved space efficiency, traverse the string backward 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 Solution)
- > Time Complexity: O(n), as we traverse the string once.
- > Space Complexity: O(1), as no extra data structures are used.
đź“‹ Dry Run
Input: s = "fly me to the moon"

Output: 4
✨ Pro Tips for Interviews
- 
Clarify constraints: - Can the string be empty?
- Are there multiple spaces between words?
 
- 
Optimize for edge cases: - Input with only spaces (" "→0).
- Single-word input ("hello"→5).
 
- Input with 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! 🚀
 
 
              
 
    
Top comments (1)
Follow Me on GitHub 🚀
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!