LeetCode Problem Workspace
Length of Last Word
Determine the length of the last word in a string using a focused string-driven approach to handle spaces and trailing characters.
1
Topics
9
Code langs
3
Related
Practice Focus
Easy · String-driven solution strategy
Answer-first summary
Determine the length of the last word in a string using a focused string-driven approach to handle spaces and trailing characters.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for String-driven solution strategy
To solve "Length of Last Word", quickly trim trailing spaces and scan backward to identify the last word. Count consecutive non-space characters to obtain its length. This approach directly leverages string handling without extra data structures, ensuring efficiency for typical interview constraints.
Problem Statement
Given a string s containing words separated by spaces, return the length of the last word. A word is defined as a maximal substring of non-space characters.
You must handle strings with trailing spaces correctly. For example, " fly me to the moon " should return 4, because the last word is "moon" despite leading and trailing spaces.
Examples
Example 1
Input: s = "Hello World"
Output: 5
The last word is "World" with length 5.
Example 2
Input: s = " fly me to the moon "
Output: 4
The last word is "moon" with length 4.
Example 3
Input: s = "luffy is still joyboy"
Output: 6
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.
Solution Approach
Trim and Split Method
Remove leading and trailing spaces, split the string by spaces, and return the length of the last element. This method directly leverages string manipulation but may allocate extra memory for the array.
Backward Scan Without Splitting
Scan the string from the end, skipping trailing spaces, then count characters until a space or the beginning of the string. This approach is space-efficient and handles large strings without extra storage.
Optimized Index Tracking
Track the index of the last space while iterating from the end. Compute the length as the difference between string end and last space index. This reduces operations by avoiding full backward scans when unnecessary.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(n) in all approaches, where n is the length of the string, since each character is inspected at most once. Space complexity varies: O(n) for the split approach, O(1) for backward scanning or index tracking.
What Interviewers Usually Probe
- Expectations of handling trailing spaces correctly.
- Interest in string traversal without extra data structures.
- Observation of O(1) space solutions for interview optimization.
Common Pitfalls or Variants
Common pitfalls
- Failing to ignore trailing spaces, leading to off-by-one errors.
- Using split blindly, which may allocate unnecessary memory.
- Counting spaces instead of word characters, miscalculating length.
Follow-up variants
- Return the last word itself instead of its length.
- Compute the length of the first word or any k-th word in a string.
- Handle punctuation or non-letter characters as part of words.
FAQ
What is the most efficient approach for Length of Last Word?
A backward scan without splitting is most efficient, giving O(n) time and O(1) space by counting non-space characters from the end.
Do trailing spaces affect the result?
Yes, trailing spaces must be skipped; otherwise, the algorithm may return an incorrect length.
Can I use built-in split functions?
Yes, but splitting allocates extra memory and may be less efficient for very long strings.
How do I handle a string with a single word?
The last word is the entire string, so return its length after trimming any spaces.
Does the string-driven solution pattern generalize?
Yes, scanning and counting characters from the end is a common string-driven pattern applicable to other word-length or parsing problems.
Solution
Solution 1: Reverse Traversal + Two Pointers
We start traversing from the end of the string $s$, find the first character that is not a space, which is the last character of the last word, and mark the index as $i$. Then continue to traverse forward, find the first character that is a space, which is the character before the first character of the last word, and mark it as $j$. Then the length of the last word is $i - j$.
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 - jContinue Practicing
Continue Topic
string
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
String-driven solution strategy
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward