Difficulty: Easy | Acceptance: 58.80% | Paid: No Topics: String
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.
- Examples
- Constraints
- Built-in Functions
- Reverse Iteration
- Two Pointers
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.
Constraints
1 <= s.length <= 10⁴
s consists of only English letters and spaces ' '.
There will be at least one word in s.
Built-in Functions
Intuition Use built-in string functions to trim trailing spaces, split the string into words, and return the length of the last word.
Steps
- Trim trailing spaces from the string
- Split the string by spaces
- Return the length of the last element in the resulting array
python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.rstrip().split()[-1])
Complexity
- Time: O(n)
- Space: O(n)
- Notes: Simple and readable, but uses extra space for the split array.
Reverse Iteration
Intuition Start from the end of the string and count characters until we encounter a space, skipping any trailing spaces first.
Steps
- Start from the last character
- Skip all trailing spaces
- Count characters until we hit a space or reach the beginning
- Return the count
python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
Complexity
- Time: O(n)
- Space: O(1)
- Notes: Optimal space complexity with a single pass from the end.
Two Pointers
Intuition Use two pointers to mark the start and end of the last word, then calculate the difference.
Steps
- Move the end pointer to skip trailing spaces
- Move the start pointer from end to find the beginning of the last word
- Return the difference between end and start
python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
end = len(s) - 1
while end >= 0 and s[end] == ' ':
end -= 1
start = end
while start >= 0 and s[start] != ' ':
start -= 1
return end - start
Complexity
- Time: O(n)
- Space: O(1)
- Notes: Similar to reverse iteration but uses two pointers for clarity.