Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

LeetCode 151: Reverse Words in a String, Two Approaches Explained

Reverse word order, normalize spaces, and compare a manual scan with whitespace splitting for LeetCode 151. Both collection-based solutions use O(n) time and space.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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 blue becomes blue is sky the.
  • hello world becomes world hello.
  • a good example becomes example 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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. Initialize an empty list of words and an index at the start of the string.
  2. Advance past spaces. If the index reaches the end, stop.
  3. Record the current index as the word start, then advance until a space or the end.
  4. Save the substring from the recorded start to the current index; repeat from the space-skipping step.
  5. 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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.