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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To solve Reverse Words in a String, reverse the order of the words—not the letters within them—and emit exactly one space between words. The straightforward approach scans the input and collects each word; the shorter approach uses a language’s whitespace-splitting helper. Both take O(n) time and O(n) auxiliary space, so “optimized” here means simpler tokenization, not a better asymptotic space bound.

What LeetCode’s problem asks you to do

The assignment called “Leetcode 150 | Day 8” matches LeetCode problem 151, Reverse Words in a String. Its definition of a word is a sequence of non-space characters. Given words separated by one or more spaces, return them in reverse order with one space between each pair, and no leading or trailing spaces.

For example, the sky is blue becomes blue is sky the. The letters in sky remain in their original order. Leading, trailing, and repeated spaces in the input do not carry through to the output.

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.

The stated constraints are a string length from 1 to 104, 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.

Approach 1: scan and collect words

A manual scan makes the spacing rules explicit. Skip spaces until a word begins, record its start, advance to the next space or the end of the string, and save that substring. Repeat until the input is consumed. Then reverse the collected word list and join it with one literal space.

  1. Set a position at the beginning of the string.
  2. Skip any spaces at the current position. If the end is reached, stop.
  3. Mark the start of the next word, then advance until a space or the end of the string.
  4. Save the substring from the marked start up to the current position.
  5. After scanning, reverse the saved words and join them with one space.

Skipping spaces before each word handles leading spaces and repeated separators; stopping at the end handles trailing spaces. Joining with a single separator ensures the result has normalized spacing regardless of the input.

Why the scan is O(n)

Each character is visited a bounded number of times: the scan advances through spaces and word characters, and the word substrings together account for the input’s non-space characters. Reversing and joining the words also takes time proportional to the output size. The word list and returned string require O(n) auxiliary space in the cited solution analysis.

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

Approach 2: split on whitespace, reverse, and join

When the language provides a whitespace-oriented split that discards leading and trailing whitespace and does not produce empty tokens for repeated separators, the solution can be expressed as three operations: split into words, reverse the sequence, and join with a literal single space.

For example, in Python the core expression is ' '.join(s.split()[::-1]). Here, the no-argument split() treats runs of whitespace as separators and omits empty tokens at the edges. The join step supplies the required single spaces in the result.

This approach also takes O(n) time and O(n) auxiliary space in the cited solution analysis: it creates a word sequence and a returned string. Its compactness depends on the language’s exact split behavior. Splitting on a literal space can retain empty tokens around leading, trailing, or repeated spaces, so verify the chosen operation’s semantics rather than assuming all methods named split behave alike.

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

Manual scan vs. whitespace splitting

Choice Strength Trade-off Complexity in the cited analysis
Manual scan and word list Explicit control over where words begin and end, and how spaces are discarded. More parsing steps and code to maintain. O(n) time; O(n) auxiliary space.
Whitespace split, reverse, and join Short implementation when the language helper handles repeated and edge whitespace correctly. Behavior varies by language and by the split method used; a literal-delimiter split may retain empty tokens. O(n) time; O(n) auxiliary space.

The available analysis supports the same asymptotic bounds for both approaches; it does not establish that one runs faster in practice. Choose based on whether your language’s whitespace helper matches the problem’s rules and whether you prefer concise code or explicit tokenization.

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

What “in-place with O(1) extra space” changes

The common solutions above build a word collection and a returned string, so they do not meet a constant-extra-space requirement. 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?” The condition matters: mutable storage can make an in-place transformation possible, while creating a fresh character array from an immutable string requires accounting for that allocation.

For a mutable character array, one implementation idea is to reverse the full character sequence, reverse the characters within each word to restore each word’s spelling, and compact spaces while scanning. That is a different implementation problem from collecting words or calling a split helper; whether it satisfies the space constraint depends on the language’s representation and on avoiding additional storage proportional to the input.

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.