Reverse Words in a String

Medium

Topics
StringTwo Pointers

Given an input string s, reverse the order of the words. Words are separated by one or more spaces; the result must have single spaces between words and no leading or trailing spaces.

Example 1

intheskyisblue
outblueisskythe
Word order reverses but each word keeps its own spelling, and extra or leading whitespace must be collapsed to single spaces. The in-place version reverses the whole string and then each word again; splitting and rejoining is the simpler route.
Chips are the words before and after.
Input:  s = "the sky is blue"
Output: "blue is sky the"

Example 2

inhelloworld
outworldhello
Input:  s = "  hello world  "
Output: "world hello"

Constraints

  • 1 <= s.length <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Three things happen at once: split on runs of whitespace, reverse the order, and normalise the separators to a single space. A split that collapses runs and drops empty fields does the first and third for free, which is why the one-liner is the honest answer in a language that has one.

In an interview the follow-up is to do it in place on a character array, which is the two-step trick: reverse the entire array, then reverse each word back. That turns the ordering problem into two local reversals and needs no extra buffer.

Approach

  1. Split on whitespace, discarding empty fields.
  2. Reverse the resulting list.
  3. Join with a single space.

Dry Run

"the sky is blue"    ->  "blue is sky the"
"  hello world  "    ->  "world hello"        leading and trailing space dropped
"a good   example"   ->  "example good a"     the run of three spaces collapses

the in-place variant on a char array

  reverse everything        "elpmaxe   doog a"
  reverse each word back    "example   good a"
  then compact the runs     "example good a"

Complexity

  • Time — O(n): split, reverse and join are each linear.
  • Space — O(n) for the word list and the result. The char-array variant is O(1) auxiliary beyond the array itself.

Common Pitfalls

  • Splitting on a single space literal rather than on whitespace runs. On "a good example" that yields empty fields and the join reproduces them, giving "example good a" instead of "example good a".
  • Trimming the ends but not collapsing interior runs, which passes the first example and fails the third.
  • Reversing the characters of each word as well as the order of the words. Only the word order reverses.
  • Claiming O(1) space while using split. The word list is O(n); the in-place version is the one that earns the O(1) claim, and only on a mutable array.
  • In the in-place variant, reversing the words first and the whole array second. The order matters: whole array first, then each word.

Full Solution — all languages

class Solution:
    def reverseWords(self, s):
        return " ".join(reversed(s.split()))
SensAI
Beta
Tap the mic to stop voice mode