#58 Length of Last Word
the problem
In plain words
A string holds English letters and spaces, with at least one word in it. A word is a run of letters with no space inside. Return how many letters the last word has — spaces at the very end don't count.
in s = "Hello World"
out 5
The last word is "World".
in s = " fly me to the moon "
out 4
Trailing spaces are ignored; the last word is "moon".
in s = "luffy is still joyboy"
out 6
- 1 ≤ s.length ≤ 10⁴
- Only English letters and ' '
- At least one word
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternString parsing
Only the end of the string matters. Walk backwards: skip the trailing spaces, then count letters until the next space (or the start).
solutions
From brute force to optimal
Let the library cut the string into words and take the last one.
s.trim()drops the spaces at both ends.split("\\s+")cuts on runs of spaces.- Return the last piece's length.
trim and split each walk the whole string once.
A trimmed copy plus a new String for every word.
class Solution { public int lengthOfLastWord(String s) { String[] words = s.trim().split("\\s+"); // trim, then split on runs of spaces return words[words.length - 1].length(); }}After trimming, the last word starts right after the last space.
- t = s.trim().
- Answer = t.length() − 1 − t.lastIndexOf(' ').
trim and lastIndexOf are each one scan.
trim may build a copy of almost the whole string.
class Solution { public int lengthOfLastWord(String s) { String t = s.trim(); // a copy without the spaces at the ends return t.length() - 1 - t.lastIndexOf(' '); // no space at all -> lastIndexOf is -1 }}One index walks left: skip spaces, then count letters.
- i = s.length() − 1.
- While s[i] is a space, i−−.
- While i ≥ 0 and s[i] is a letter, count++ and i−−.
- Return count.
Worst case (one long word) touches each char once.
One index and one counter — no copies.
class Solution { public int lengthOfLastWord(String s) { int i = s.length() - 1; while (i >= 0 && s.charAt(i) == ' ') i--; // skip trailing spaces int length = 0; while (i >= 0 && s.charAt(i) != ' ') { // count letters until a space or the start length++; i--; } return length; }}in the room
How to say it in the interview
talk track
- Clarify: leading, trailing or repeated spaces? (All possible.) At least one word? (Yes.)
- Offer the one-liner with
trim().split("\\s+"), name its O(n) extra space, then write the O(1)-space backward scan. - Point at the
i >= 0check beforecharAt(i)— it preventsStringIndexOutOfBoundsExceptionon a single word.
traps
- Checking
s.charAt(i)beforei >= 0→StringIndexOutOfBoundsException. - Returning the length of the last token from
split(" ")without trimming — a leading-space input still works, but the habit breaks other problems.
what they ask next
Follow-ups
Words may be separated by tabs or newlines too?
Use Character.isWhitespace(c) instead of == ' ', or split("\\s+").
Return the last word itself?
Remember where the word ends, scan to its start, then one s.substring(start, end) — a single O(k) copy.
before you submit
Edge cases to test
- Trailing spaces: "moon " → 4, not 0.
- One word, no spaces: "day" → 3 (the loop must stop at index 0, not read index −1).
- Several spaces between words: a plain
split(" ")creates empty tokens.
practise next
Similar problems
- #125Valid PalindromeEasyin Two Pointers
- #71Simplify PathMediumin Stacks