The task is to reverse the order of the words, not the letters inside them, then return the words separated by exactly one space. A straightforward solution scans and collects words; a shorter alternative uses a language’s whitespace-splitting helper. Both take O(n) time and O(n) auxiliary space. The supplied series title says “Leetcode 150,” but this specific problem is numbered 151 on LeetCode.
What should the result do?
LeetCode defines a word as a sequence of non-space characters. Words are separated by one or more literal spaces. The output reverses word order, removes leading and trailing spaces, and puts one space between each pair of words.
As an Amazon Associate I earn from qualifying purchases.
the sky is bluebecomesblue is sky the.hello worldbecomesworld hello.a good examplebecomesexample good a.
The stated constraints are 1 ≤ s.length ≤ 104; the input contains English uppercase and lowercase letters, digits, and the literal space character, with at least one word. These constraints do not establish behavior for arbitrary Unicode whitespace.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Approach 1: scan, collect, and join
A manual scan makes the spacing rules explicit. Skip any spaces at the current position, mark the beginning of a word, then move forward until the next space or the end of the string. Save that word and repeat. Once the scan is complete, reverse the collected words and join them using one literal space.
#1 Best Overall
- Initialize an empty list of words and an index at the start of the string.
- Advance past spaces. If the index reaches the end, stop.
- Record the current index as the word start, then advance until a space or the end.
- Save the substring from the recorded start to the current index; repeat from the space-skipping step.
- Reverse the list and join its words with one space.
For example, scanning a good example saves ["a", "good", "example"]. Reversing the list and joining produces example good a, without needing separate fixes for the leading, trailing, or repeated spaces.
Complexity
The scan visits each character a bounded number of times, so the running time is O(n). The word list and returned string require O(n) auxiliary space in total. This is easy to trace and gives direct control over how tokens are found, though it involves more parsing code than the built-in approach.
Rank #2
Approach 2: split on whitespace, reverse, and join
If the language provides a whitespace-oriented split operation that discards empty tokens created by leading, trailing, or repeated spaces, the implementation can be concise: split into words, reverse that sequence, and join it with one literal space. In Python, for example, s.split() without an explicit separator splits on runs of whitespace and omits empty strings at the ends; joining the reversed result with " " produces the required spacing.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Do not assume every operation named split behaves that way. Splitting on a literal space may preserve empty tokens, so reversing and joining those tokens can leave extra spaces in the answer. Check the chosen language’s documented semantics; whitespace helpers such as Go’s strings.Fields and Rust’s split_whitespace are also used for this kind of tokenization. Java implementations may trim and then split with a whitespace expression, but details depend on the exact expression and handling of empty input.
Complexity and trade-off
The split-based solution is also O(n) time and O(n) auxiliary space: it creates a word sequence and a result. It is shorter when the language’s helper matches the prompt’s rules, but provides less visible control over tokenization. The available complexity analysis does not establish that it is faster in practice than a manual scan.
Which approach should you choose?
| Consideration | Manual scan and collection | Whitespace split and join |
|---|---|---|
| How words are found | Explicitly skips spaces and records word boundaries. | Delegates tokenization to a language helper. |
| Spacing behavior | Can implement the prompt’s literal-space rules directly. | Correct only if the helper handles leading, trailing, and repeated spaces as needed. |
| Implementation | More parsing steps, but each is visible. | Less code when the language’s split semantics fit. |
| Complexity | O(n) time and O(n) auxiliary space. | O(n) time and O(n) auxiliary space. |
Use the scan when you want transparent boundary handling or need precise control over tokenization. Use built-in splitting when its behavior is clear and aligned with the input contract. Neither collection-based approach improves the asymptotic space requirement.
Rank #4
What does the in-place O(1)-space follow-up mean?
LeetCode’s follow-up asks: “If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?” This is a separate constraint from the two collection-based methods above. Those methods allocate storage proportional to the input.
The condition matters: strings are immutable in some languages, while others offer a mutable character buffer. A common idea for a mutable character array is to reverse the whole sequence, then reverse the characters within each word and compact spaces. That is an implementation direction, not the collection-based solution described here; whether it truly uses O(1) extra space depends on the representation and on avoiding a fresh array or other input-sized allocation. See the follow-up on the official problem page.
Quick Recap
Common mistakes to avoid
- Reversing every word’s characters instead of reversing the words’ order.
- Leaving leading or trailing spaces in the result.
- Preserving runs of spaces instead of emitting one separator between words.
- Assuming literal-delimiter splitting and whitespace splitting produce the same tokens.
- Calling a solution O(1) extra space while it creates a new input-sized character array or word list.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




