Read the final space-delimited token
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Return the last nonempty token separated by ASCII spaces. Ignore trailing spaces. Tabs and other whitespace belong to the token. Return an empty string when there is no token.
Examples
"""""hello world ""world"" one""one"Constraints
0–10,000 UTF-16 code units. Preserve original spelling and case.
Review lesson: Slicing, searching, and replacementA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- Find the final character that is not a space.
- Walk backward from there to the preceding space.
- Slice the half-open interval between those boundaries.
Worked solution
Try your own approach first, then compare the reasoning.
function finalToken(text) {
let end = text.length;
while (end > 0 && text[end - 1] === " ") end--;
let start = end;
while (start > 0 && text[start - 1] !== " ") start--;
return text.slice(start, end);
}
Two backward scans find the end and beginning of the final token. Unlike splitting the entire input, the scan needs no array of all words. The returned slice preserves tabs and supplementary characters because only ASCII spaces define boundaries.
Complexity
O(n) time and O(k) result space for a k-code-unit token; O(1) working state.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.