Length of Last Word LeetCode Solution

Last updated on January 19th, 2025 at 06:04 pm

Here, we see a Length of Last Word LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

String

Level of Question

Easy

Length of Last Word LeetCode Solution

Length of Last Word LeetCode Solution

1. 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.

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.

2. Coding Pattern Used in Solution

The provided code in all four languages solves the problem of finding the length of the last word in a given string. The coding pattern is “String Traversal” or “Iterative String Parsing”, as the solution involves iterating through the string to extract and compute the desired result.

3. Code Implementation in Different Languages

3.1 Length of Last Word C++

class Solution {
public:
    int lengthOfLastWord(string s) {
        int A = 0;
        for (int i=s.size()-1; i>=0; --i) {
            if (s[i] != ' ') ++A;
            else if (A) return A;
        }
        return A;        
    }
};

3.2 Length of Last Word Java

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                length++;
            } else {
                if (length > 0) return length;
            }
        }
        return length;        
    }
}

3.3 Length of Last Word JavaScript

var lengthOfLastWord = function(s) {
    let trimmedString = s.trim();
    return trimmedString.length - trimmedString.lastIndexOf(' ') - 1;   
};

3.4 Length of Last Word Python

class Solution(object):
    def lengthOfLastWord(self, s):
        s = s.strip()       # Remove the spaces at the beginning and end
        length = 0
        for i in range(len(s)):
            if s[i] == " ":
                length = 0
            else:
                length += 1    # Inside one word
        return length

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n)O(1)
JavaO(n)O(1)
JavaScriptO(n)O(n)
PythonO(n)O(1)

Scroll to Top