#58
Length of Last Word
EasyStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution avoids unnecessary splitting by scanning the string from the end to find the last word directly. This is more efficient as it only requires a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Trim any trailing spaces from the string.
- 2Step 2: Initialize a counter for the length of the last word.
- 3Step 3: Traverse the string from the end until a space is encountered or the beginning of the string is reached, counting characters.
solution.py10 lines
1def length_of_last_word(s):
2 s = s.rstrip()
3 length = 0
4 for char in reversed(s):
5 if char == ' ':
6 if length > 0:
7 break
8 else:
9 length += 1
10 return lengthℹ
Complexity note: The time complexity is O(n) because we traverse the string once. The space complexity is O(1) since we use a constant amount of extra space.
- 1Trimming spaces is crucial to avoid counting them as part of the last word.
- 2Iterating from the end of the string is more efficient than splitting the entire string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.