- Interview Questions
- /
- Problems
- /
- Length of Last Word
Length of Last Word
Return how many characters are in the final word of a string that may end with spaces. A short exercise in scanning from the end and handling trailing whitespace. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given a string s made of words and spaces. A word is a maximal run of non-space characters.
Return the length of the last word in s. The string may have spaces at the start, at the end, or several in a row between words; those spaces are never part of a word. There is always at least one word.
Example 1
- Input
- s = "open the door"
- Output
- 4
The last word is "door".
Example 2
- Input
- s = " keep going "
- Output
- 5
Trailing spaces are ignored, so the last word is "going".
Example 3
- Input
- s = "x"
- Output
- 1
Constraints
- 1 ≤ s.length ≤ 10⁴
- s contains only English letters and spaces.
- s contains at least one word.
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Length of Last Word in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Length of Last Word
Pattern: Scan from the end
Only the end of the string matters, so start there. Two phases:
- Skip any trailing spaces.
- Count characters until you hit a space or run off the front.
That count is the answer. You never look at the earlier words, so the work is proportional to the length of the last word plus the trailing spaces, not the whole string.
Approach 1: Split into words
Split on whitespace and take the length of the last piece (s.split() in Python, s.trim().split(/\s+/) in JavaScript). Simple, but it builds a list of every word just to read one.
Time O(n) · Space O(n)
Approach 2: Reverse scan
Set i to the last index.
- While
s[i]is a space, moveileft. - While
i >= 0ands[i]is not a space, increment a counter and moveileft. - Return the counter.
Time O(n) worst case, often much less · Space O(1)
| Approach | Time | Space |
|---|---|---|
| Split into words | O(n) | O(n) |
| Reverse scan | O(n) worst case, often much less | O(1) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Length of Last Word solution in Python
def length_of_last_word(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 lengthLength of Last Word solution in JavaScript
function lengthOfLastWord(s) {
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') i--;
let length = 0;
while (i >= 0 && s[i] !== ' ') {
length++;
i--;
}
return length;
}Common mistakes
- Forgetting trailing spaces, which makes the answer 0 for inputs like "hi ".
- Using `s.split(' ')` and taking the last piece, which is an empty string when the input ends with a space.
- Running the index below 0 when the string has a single word with no leading space.
- Counting from the first space found from the left, which gives the first word instead of the last.
What interviewers look for
This one is about being precise with boundaries. Say both phases out loud, then trace "a " and " lonely" to show you handle trailing spaces and running off the front.
Mention that the reverse scan uses O(1) memory and often finishes early, while the split version always processes the whole string.
Follow-up questions
What if words could be separated by tabs and newlines too?
Replace the "is a space" check with a general whitespace check such as `str.isspace()` or a regex test. The two-phase scan stays the same.
How would you return the length of the k-th word from the end?
Repeat the two phases k times: skip spaces, then skip a word, counting only on the k-th word. It is still a single right-to-left pass.
What if the string were a stream you can only read forward?
Keep two counters: the length of the current word and the length of the most recent completed word. On a space, if the current length is positive, save it and reset. At the end, return the current length if positive, otherwise the saved one.
Companies that ask Length of Last Word
Length of Last Word is tagged by 75 companies in our interview dataset. The score shows how often it comes up at each company.
- Carvana100%
- Mailchimp100%
- Transunion98%
- Daimler95%
- Life36092%
- Palantir90%
- Offerup86%
- Te Connectivity84%
- Intellia Therapeutics83%
- Goodnotes81%
- Zulily80%
- Astera Labs78%
- Miro78%
- Culture Amp77%
- Globant76%
- Retailmenot76%
- Rocket Software75%
- Micron Technology75%
- Zocdoc73%
- Zimmer Biomet73%
- Nebius70%
- Handshake68%
- Bayer67%
- Benevity66%
and 51 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required