Solving tips
- Recognize the answer lives entirely at the right end, so scan backwards rather than parsing the whole string.
- From the last index, first skip trailing spaces, then count non-space characters until you hit a space or the start; O(n) time, O(1) space.
- The one-liner len(s.split()[-1]) works but allocates every word β mention the O(1)-space reverse scan for the follow-up.
- Pitfall: forgetting the trailing-space skip returns 0, and always check i >= 0 before indexing s[i].
Problem
Given a string s made of letters and spaces, return the length of its last word. A word is a maximal run of non-space characters. The string is guaranteed to contain at least one word, but it may begin or end with any number of spaces, and words may be separated by multiple spaces.
Examples
- Input:
s = "Hello World" β Output: 5
The last word is "World", which has 5 letters.
- Input:
s = " fly me to the moon " β Output: 4
Trailing spaces are ignored; the last word is "moon".
- Input:
s = "luffy is still joyboy" β Output: 6
The last word is "joyboy".
Constraints
1 <= len(s) <= 10^4
s consists only of English letters and spaces ' '
- At least one word is present
Linear time is expected; the interesting follow-up is doing it in O(1) extra space.
Think about it first
Hint 1
What does Python's `split()` (with no arguments) do with leading, trailing, and repeated spaces?
Hint 2
To avoid building any new strings at all, which end of the string should you start reading from?
Hint 3
Scan from the right: first skip trailing spaces, then count characters until you hit a space or the start of the string. That count is the answer.
TL;DR
Scan backwards from the end (skip spaces, then count letters) β O(n) time, O(1) space.
Approach 1 β Brute force: split into words
The direct translation of the statement: cut the string into words, take the last one, return its length. Pythonβs argument-less split() already handles leading/trailing/repeated spaces.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
words = s.split()
last = words[-1]
return len(last)
Complexity: O(n) time, O(n) extra space β split materializes every word.
The constraints (n β€ 10^4) donβt kill this at all; what βkillsβ it in an interview is the follow-up question βcan you do it without allocating a copy of the string?β β we only need the last word, yet we built all of them.
Approach 2 β Reverse scan, no allocation
The insight: the answer lives entirely at the right end of the string. Walk from the last character leftwards: first step over trailing spaces, then count non-space characters until the next space (or the beginning). Nothing before that point matters.
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
Walkthrough on s = " fly me to the moon " (length 28):
i starts at 27. Characters 27 and 26 are spaces, so the first loop drops i to 25 (the n of moon).
- Second loop counts non-spaces:
n (i=25), o (24), o (23), m (22) β length reaches 4.
- At
i = 21 the character is a space, so the loop stops.
- Return
4. Matches the expected output.
Complexity: O(k) time where k is the length of the trailing spaces plus the last word β at most O(n), and it never touches the front of the string. O(1) extra space.
Common pitfalls
- Splitting on a literal space,
s.split(" "), instead of s.split(): repeated or trailing spaces then produce empty strings, and the last element may be "".
- Forgetting the trailing-space skip in the reverse scan β
"moon " would immediately read a space and return 0.
- Off-by-one on the loop guard: check
i >= 0 before indexing s[i], or a string of all spaces (not possible here, but a habit worth keeping) walks off the front.
Pattern takeaway
When the answer depends on only one end of a sequence, scan from that end and stop as soon as you have it β donβt preprocess the whole input. βParse everything, then pickβ is fine as a first answer, but the O(1)-space refinement (walk the indices yourself) is a standard interview follow-up for string problems.