Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
Scan from the END of the string. First skip any trailing spaces, then count consecutive non-space characters until you hit a space or the start. That count is the answer — O(n) time, O(1) space, no split() needed.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you handle trailing whitespace correctly and whether you reach for an O(1)-space reverse scan instead of reflexively calling split() and indexing the last element.
Where candidates slip
Counting from the right without first skipping trailing spaces, so "a " returns 0; or using s.split(' ')[-1] which breaks on multiple spaces by yielding empty strings.
How to stand out
Mention that split() is fine but allocates the whole list; offer the O(1)-space two-phase reverse scan and note the trailing-space trap explicitly before coding.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewi = len(s) - 1s[i] == ' ' and i >= 0?YesNoExplore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
Split and Take Last (Library)
1Hint 1Explore hintHide hint
The language can tokenize the string for you. What does split do, and which element do you then want?
2Hint 2Explore hintHide hint
In Python, str.split() with no argument collapses runs of whitespace and ignores leading/trailing spaces — convenient here.
3Hint 3Explore hintHide hint
Split into words, then take the last word and return its length. Beware split(' ') with an explicit space argument: it keeps empty strings between consecutive spaces.
A · Core idea
The most direct solution leans on the standard library: split the string into a list of words and return the length of the last one. It reads almost like the problem statement, which is its main virtue in an interview — you can produce it in seconds and then immediately discuss its weaknesses.
Why the splitting variant matters. In Python, s.split() with no argument is the safe form: it treats any run of whitespace as a single delimiter and discards leading and trailing whitespace, so " a b ".split() is ['a', 'b']. Contrast s.split(' ') with an explicit space: that splits on every single space and keeps the empty strings between consecutive spaces, so "a b".split(' ') is ['a', '', 'b'] — taking [-1] could hand you an empty string from a trailing space. In Java, s.trim().split("\\s+") is the parallel safe form. Knowing which split semantics you're using is the difference between correct and subtly broken.
Why we don't always ship it. Splitting allocates a list holding every word even though we only ever need the last one's length. For a string with thousands of words that's a lot of throwaway memory. The interviewer who asks 'can you do it in O(1) extra space?' is steering you toward the reverse scan. So present this as the readable baseline, then offer the optimal.
Why it's still worth stating. It's the version you'd actually write in production where clarity beats micro-optimization, and it demonstrates you know your language's string API. Just be explicit about the whitespace-collapsing semantics so the interviewer trusts you understand the edge cases.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
s = " fly me to the moon "split
s.split() collapses runs and trims
['fly', 'me', 'to', 'the', 'moon']4C · Code with teaching comments
Reference implementation previewpublic int lengthOfLastWord(String s) { String[] words = s.trim().split("\\s+"); return words[words.length - 1].length(); }Explore the full codeHide the full code
D · Why it works and complexityO(n) timeO(n) spaceOpen the invariant and proofExplore the proofHide the proof
The whole correctness of the one-liner hinges on whether your language's split collapses whitespace runs. split() (no arg, Python) and trim().split("\\s+") (Java) are safe; split(' ') is a trap. Naming that distinction unprompted signals real fluency.
ComplexityO(n) time, O(n) space — split() walks the whole string once (O(n)) and allocates a list of all words (O(n) extra space). Indexing the last element and taking its length is O(1).
E · Edge cases and pitfalls5s = "a" — split() → ['a']; last word length 1.Explore edge casesHide edge cases
Edge cases handled
s = "a"split() → ['a']; last word length 1.s = "day "Trailing space trimmed by split(); ['day'] → 3. Would break with split(' ')[-1] which yields ''.
Pitfalls
- Using s.split(' ')[-1] with an explicit space — multiple/trailing spaces produce empty strings.
- Forgetting trim() in Java before split("\\s+") on a string that starts with whitespace.
- Allocating the full word list when only one length is needed — flagged when O(1) space is requested.
Approach 2 of 2 · Optimal
Reverse Scan, O(1) Space (Optimal)
1Hint 1Explore hintHide hint
You only need the LAST word. Which end of the string should you start from to avoid tracking every word?
2Hint 2Explore hintHide hint
Start at the last index. First move left past any trailing spaces. Where you stop is the last character of the last word.
3Hint 3Explore hintHide hint
Now count leftward while characters are non-space. Stop at the first space (or the string start). The count is the length.
A · Core idea
Because the question asks only about the last word, the efficient move is to scan from the right end of the string and stop the moment we've measured one word. This avoids allocating any list and uses only a pointer and a counter.
Phase one — skip trailing spaces. Inputs like "Hello World " end in spaces, and the last word's final character sits to the left of them. So we start i at the last index and decrement while s[i] is a space. When this loop stops, i points at the last non-space character — the true end of the last word. Skipping this phase is the single most common bug: counting immediately from len(s) - 1 on a space-terminated string yields 0 because the first thing you see is a space.
Phase two — count the word. From the end of the last word, we keep walking left and incrementing a counter while s[i] is a non-space character. The loop also guards i >= 0 so a string that is a single word (no leading space) terminates at the start instead of indexing out of bounds. When we hit a space — the gap before the last word — or run off the front, the counter holds exactly the last word's length.
Why right-to-left beats left-to-right here. A left-to-right scan would have to track the length of every word, resetting on each space, because it can't know which word is last until it reaches the end. Scanning from the right, the first word we encounter is the one we want, so we can return as soon as we've measured it. Same O(n) worst case, but conceptually simpler and with no wasted bookkeeping. This is the general lesson: when only a boundary element matters, start from that boundary.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
s = "Hello World "Interactive diagram
Pointer journey on a trailing-space input
phase 1i first slides left past spaces, then counts the word until the gap before it.
5C · Code with teaching comments
D · Why it works and complexityO(n) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Two tight phases — 'skip the trailing noise' then 'measure the real thing' — is a reusable shape. You'll see the same skeleton in trimming, in parsing the last token of a path, and in reading a number off the end of a string.
ComplexityO(n) time, O(1) space — A single index walks from the end leftward at most n positions across both phases combined. Only a couple of integer variables are used, so O(n) time and O(1) extra space.
E · Edge cases and pitfalls6s = " " (hypothetical all spaces) — Phase 1 walks i to -1, phase 2 never runs → returns 0. Constraints guarantee at least one word, but the code is safe anyway.Explore edge casesHide edge cases
Edge cases handled
s = " " (hypothetical all spaces)Phase 1 walks i to -1, phase 2 never runs → returns 0. Constraints guarantee at least one word, but the code is safe anyway.s = "a"No trailing spaces; phase 2 counts 'a' then i hits -1 → returns 1.s = "abc "Phase 1 skips the one trailing space, phase 2 counts 'abc' → 3.
Pitfalls
- Skipping phase 1 — counting from the last index directly returns 0 on a trailing-space input.
- Omitting the i >= 0 guard in phase 2 — a single-word string indexes out of bounds.
- Using a for loop that doesn't break, recomputing across every word unnecessarily.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic int lengthOfLastWord(String s) { int i = s.length() - 1; while (i >= 0 && s.charAt(i) == ' ') { i--; }Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1Not skipping trailing spaces
On "Hello World " the last index is a space, so counting immediately gives 0. You must move past trailing spaces first.
Explore the code comparisonHide the code comparison
Not skipping trailing spaces
On "Hello World " the last index is a space, so counting immediately gives 0. You must move past trailing spaces first.
Don't write this
i = len(s) - 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length # returns 0 on trailing spacesWrite this instead
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 length2split(' ') with explicit space
Explicit-space split keeps empty strings between consecutive spaces, so [-1] can be '' on trailing/multiple spaces.
Explore the code comparisonHide the code comparison
split(' ') with explicit space
Explicit-space split keeps empty strings between consecutive spaces, so [-1] can be '' on trailing/multiple spaces.
Don't write this
return len(s.split(' ')[-1]) # '' on 'a b 'Write this instead
return len(s.split()[-1]) # no-arg split collapses whitespace3Missing bounds guard in count loop
Without i >= 0, a single-word string like 'a' decrements i to -1 and then indexes s[-1] (Java throws, Python wraps to the wrong char).
Explore the code comparisonHide the code comparison
Missing bounds guard in count loop
Without i >= 0, a single-word string like 'a' decrements i to -1 and then indexes s[-1] (Java throws, Python wraps to the wrong char).
Don't write this
while (s.charAt(i) != ' ') {
length++;
i--;
} // StringIndexOutOfBounds when i reaches -1Write this instead
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}Revise
Carry the pattern into the interview
Pattern to remember
Reverse scan with two phases (skip trailing, then count)
Code pattern to memorize
i = len(s) - 1
while i >= 0 and s[i] == ' ': i -= 1 # skip trailing spaces
length = 0
while i >= 0 and s[i] != ' ': i -= 1; length += 1
return lengthRules to remember
- 1Strip trailing spaces first. Inputs like
"Hello World "end in spaces; counting before skipping them gives 0. - 2Walk from the right, not the left. You only need the last word, so scanning from the end avoids tracking every word.
- 3Stop at the first space after the word — that boundary marks the start of the last word.
- 4No leading-space worry once you scan right-to-left; the right-to-left walk naturally ignores everything before the last word.
- 5`split()` works but is wasteful — it allocates the whole word list when you only need one length.
Use this pattern when
- You need information about only the last (or first) token, not all tokens
- Input may have arbitrary trailing/leading whitespace to normalize
- Constant extra space is desired — avoid building intermediate arrays
- A single linear pass from one end suffices
Choose another pattern when
- You need every word's length / all tokens → split() is justified
- Words are separated by arbitrary delimiters, not just spaces → use a proper tokenizer/regex
- You must modify words in place → different problem (Reverse Words)
- The 'word' definition includes punctuation rules → needs explicit char classification
Interview takeaway
When a problem only cares about the boundary element (last word, last digit, last segment), scanning from the relevant end with O(1) space beats splitting the whole input. Two tiny phases — skip the trailing noise, then count the real thing — solve it cleanly.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternBoundary-element reverse scan: when only the last (or first) token matters, scan from that end with O(1) space instead of splitting the whole string. The skip-then-count two-phase shape recurs in trimming and last-token parsing.
Practice queueDirect variations and pattern siblings
Direct follow-ups
- Reverse Words in a StringSame whitespace-handling skills, but you reverse the order of all words and normalize spaces.
- Reverse Words in a String IIIComing soonReverse the characters of each word in place — practice locating word boundaries.
- Number of Segments in a StringComing soonCount words instead of measuring the last — count transitions from space to non-space.