Skip to main content

Length of Last Word - LeetCode Daily Challenge

Prerna Sharma

Problem Statement

Given a string s consisting of words and spaces, return the length of the last word in the string.

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.

Try here before watching the video.

Video Solution

Java Code

class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim();
        System.out.println(s);
        return s.length() - s.lastIndexOf(" ") - 1;
    }
}

C++ Code

class Solution {
public:
    int lengthOfLastWord(string s) {
        // Trimming the string
        s.erase(s.find_last_not_of(" ") + 1);
        s.erase(0, s.find_first_not_of(" "));
        
        // Finding the length of the last word
        int lastSpaceIndex = s.find_last_of(" ");
        return s.substr(lastSpaceIndex + 1).length();
    }
};

Python Code

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.strip()
        return len(s.split()[-1]) if s else 0

Javascript Code

var lengthOfLastWord = function(s) {
    s = s.trim();
    const words = s.split(" ");
    return words[words.length - 1].length;
};

Go Code

func lengthOfLastWord(s string) int {
    s = strings.TrimSpace(s)
    words := strings.Split(s, " ")
    return len(words[len(words)-1])
}

Complexity Analysis

Time Complexity: O(N)
Space Complexity: O(N)