# Length of Last Word
**Difficulty:** EASY
[External](https://leetcode.com/problems/length-of-last-word)
Canonical: https://scaleengineer.com/dsa/problems/length-of-last-word
**Data structures:** String
**Companies:** [Adobe](https://scaleengineer.com/companies/adobe), [Amazon](https://scaleengineer.com/companies/amazon), [Apple](https://scaleengineer.com/companies/apple), [Bloomberg](https://scaleengineer.com/companies/bloomberg), [Meta](https://scaleengineer.com/companies/meta), [Microsoft](https://scaleengineer.com/companies/microsoft), [Qualcomm](https://scaleengineer.com/companies/qualcomm), [Uber](https://scaleengineer.com/companies/uber), [Yahoo](https://scaleengineer.com/companies/yahoo), [tcs](https://scaleengineer.com/companies/tcs)
---
## Problem
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.

**Constraints:**

* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.
* There will be at least one word in `s`.

# Approaches
## Using String split()
This approach leverages built-in string manipulation functions. First, we remove any leading and trailing whitespace from the string using `trim()`. Then, we split the string by spaces to get an array of all the words. The last word is simply the last element in this array, and we return its length.
**Time:** O(N) · **Space:** O(N)
**Pros:** Very concise and easy to read, as it relies on high-level built-in functions.; The logic is straightforward and directly maps to the problem's definition.
**Cons:** Less efficient in terms of memory. It creates a new trimmed string and an array to store all the words, leading to O(N) space complexity.; The overhead of regular expression matching and creating multiple string objects can make it slower than manual iteration for large strings.
### Explanation
The core idea is to break down the problem into smaller, manageable steps using standard library functions.
1.  **Trim Whitespace:** The input string might have leading or trailing spaces (e.g., `"   hello world  "`). The `s.trim()` method is called to produce a new string `"hello world"` without these extra spaces. This ensures that when we split the string, we don't get empty strings in our resulting array from trailing spaces.
2.  **Split into Words:** The trimmed string is then split into an array of words. We use `s.split(" +")` where the argument `" +"` is a regular expression that matches one or more spaces. This correctly handles cases with multiple spaces between words (e.g., `"fly me   to   the moon"`).
3.  **Get Last Word:** The resulting array contains all the words in order. The last word is at the last index of the array (`words.length - 1`).
4.  **Calculate Length:** Finally, we get the length of this last word and return it.
```java
public class Solution {
    public int lengthOfLastWord(String s) {
        // Trim the trailing and leading spaces
        String trimmedString = s.trim();
        
        // Split the string by one or more spaces
        String[] words = trimmedString.split(" +");
        
        // The last word is the last element in the array
        String lastWord = words[words.length - 1];
        
        // Return the length of the last word
        return lastWord.length();
    }
}
```
### Algorithm
*   Call `trim()` on the input string `s` to remove leading and trailing whitespace.
*   Call `split(" +")` on the trimmed string to get an array of words. The regex `" +"` handles multiple spaces between words.
*   Access the last element of the resulting array, which corresponds to the last word.
*   Return the length of this last word.

## Single Pass from the End
A more optimal approach is to iterate through the string from right to left. We can find the length of the last word in a single pass without creating any new data structures. The idea is to first skip any trailing spaces to find the end of the last word. Then, we count the characters of the last word until we encounter a space or the beginning of the string.
**Time:** O(N) · **Space:** O(1)
**Pros:** Extremely memory efficient with O(1) space complexity, as it doesn't create any new data structures.; Very fast in practice. It performs a single pass from the end and might not even scan the entire string if the last word is near the end.
**Cons:** The code is slightly more complex to write and reason about compared to the `split()` method.
### Explanation
This method avoids the overhead of creating intermediate strings and arrays, making it very efficient in terms of space.
1.  **Initialization:** We start with a `length` counter initialized to 0 and a pointer `i` set to the last index of the string (`s.length() - 1`).
2.  **Skip Trailing Spaces:** We first loop backwards from the end of the string to skip any trailing spaces. The loop `while (i >= 0 && s.charAt(i) == ' ')` continues as long as we are within the string bounds and the character is a space. After this loop, `i` will point to the last character of the last word.
3.  **Count Word Length:** Now, we start another backward loop. This loop `while (i >= 0 && s.charAt(i) != ' ')` continues as long as we are within the string bounds and the character is not a space. Inside this loop, we increment our `length` counter and decrement `i`.
4.  **Return Length:** Once this second loop finishes (either by hitting a space or the beginning of the string), the `length` variable will hold the length of the last word. We then return this value.
```java
public class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        int i = s.length() - 1;
        
        // 1. Skip trailing spaces
        while (i >= 0 && s.charAt(i) == ' ') {
            i--;
        }
        
        // 2. Count the length of the last word
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;
            i--;
        }
        
        return length;
    }
}
```
### Algorithm
*   Initialize a pointer `i` to the last index of the string `s`.
*   Move the pointer `i` to the left, skipping all trailing spaces.
*   Initialize a `length` counter to 0.
*   Once a non-space character is found, start counting. Iterate backwards and increment `length` for each non-space character.
*   Stop when a space is encountered or the beginning of the string is reached.
*   Return the final `length`.

# Solutions
### CSharp

```csharp
public class Solution {
    public int LengthOfLastWord(string s) {
        int i = s.Length - 1;
        while (i >= 0 && s[i] == ' ') {
            --i;
        }
        int j = i;
        while (j >= 0 && s[j] != ' ') {
            --j;
        }
        return i - j;
    }
}
```

### Java

```java
class Solution {
public
  int lengthOfLastWord(String s) {
    int i = s.length() - 1;
    while (i >= 0 && s.charAt(i) == ' ') {
      --i;
    }
    int j = i;
    while (j >= 0 && s.charAt(j) != ' ') {
      --j;
    }
    return i - j;
  }
}

```

### JavaScript

```javascript
/** * @param {string} s * @return {number} */ var lengthOfLastWord = function (
  s,
) {
  let i = s.length - 1;
  while (i >= 0 && s[i] === " ") {
    --i;
  }
  let j = i;
  while (j >= 0 && s[j] !== " ") {
    --j;
  }
  return i - j;
};

```

### CPP

```cpp
class Solution {
public:
  int lengthOfLastWord(string s) {
    int i = s.size() - 1;
    while (~i && s[i] == ' ') {
      --i;
    }
    int j = i;
    while (~j && s[j] != ' ') {
      --j;
    }
    return i - j;
  }
};

```

### Python

```python
class Solution:
    def lengthOfLastWord(self, s: str) -> int: i = len(s) - 1 while i >= 0 and s[i] == ' ': i -= 1 j = i while j >= 0 and s[j] != ' ': j -= 1 return i - j

```
