Skip to content
← All posts

Reverse Words in a String: Split, Reverse, Join

5 min read
leetcodeproblemmediumstrings

LeetCode 151, Reverse Words in a String, tests whether you can cleanly handle whitespace while rearranging tokens. Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The input may contain leading spaces, trailing spaces, or multiple spaces between words. Your output must have exactly one space between words, with no leading or trailing spaces.

A few examples:

  • "the sky is blue" returns "blue is sky the"
  • " hello world " returns "world hello"
  • "a good example" returns "example good a"

The words themselves do not change. Only the order flips.

inputtheskyisblueoutputblueisskythe
The words in "the sky is blue" are reversed in order to produce "blue is sky the". Each word stays intact; only the order changes.

The approach: split, filter, reverse, join

The cleanest way to solve this in Python breaks the problem into four operations:

  1. Split the string by whitespace. This produces a list of tokens, some of which may be empty strings when there are consecutive spaces.
  2. Filter out empty strings. Only actual words survive.
  3. Reverse the list of words.
  4. Join the reversed list with a single space.

Each step handles one aspect of the problem. Splitting extracts words. Filtering removes artifacts from irregular spacing. Reversing flips the order. Joining reconstructs the string with clean formatting.

Step 1: Split by whitespace

6 tokens
helloworld

Splitting " hello world " by spaces produces tokens including empty strings from leading, trailing, and consecutive spaces.

Step 2: Filter empty strings

2 words
helloworld

Remove all empty strings. Only the actual words remain.

Step 3: Reverse the list

reversed
worldhello

Reverse the order of the word list. Each word itself stays unchanged.

Step 4: Join with single space

"world hello"
world hello

Join the words with a single space between each pair. No leading or trailing spaces.

Python solution: split and reverse

def reverseWords(s):
    return " ".join(s.split()[::-1])

That is the entire solution. Python's str.split() with no arguments splits on any whitespace and automatically discards empty strings, so you do not even need the explicit filter step. The [::-1] slice reverses the list, and " ".join(...) reassembles it with single spaces.

If you want to be more explicit about what is happening:

def reverseWords(s):
    words = s.split()
    words.reverse()
    return " ".join(words)

Both versions do the same thing. The one-liner is idiomatic Python, but the expanded version makes each step visible.

Python solution: in-place style reversal

In languages like C where you work with mutable character arrays, the standard approach avoids creating a separate word list. The idea is:

  1. Reverse the entire string.
  2. Reverse each individual word within the reversed string.
  3. Clean up extra spaces.

After step 1, "the sky is blue" becomes "eulb si yks eht". After step 2, reversing each word individually gives "blue is sky the". The two reversals cancel out at the character level within each word, but the word order flips because the first reversal moved the last word to the front.

In Python, strings are immutable, so you simulate this on a list of characters:

def reverseWords(s):
    chars = list(s)

    def reverse(l, r):
        while l < r:
            chars[l], chars[r] = chars[r], chars[l]
            l += 1
            r -= 1

    n = len(chars)
    reverse(0, n - 1)

    write = 0
    i = 0
    while i < n:
        if chars[i] != " ":
            if write > 0:
                chars[write] = " "
                write += 1
            word_start = write
            while i < n and chars[i] != " ":
                chars[write] = chars[i]
                write += 1
                i += 1
            reverse(word_start, write - 1)
        i += 1

    return "".join(chars[:write])

This version is more involved but demonstrates the technique that interviewers sometimes ask about as a follow-up. It processes the string without creating a separate list of words.

Walkthrough of the split approach

Take the input " hello world ".

Split: s.split() produces ["hello", "world"]. Python's default split handles the leading spaces, trailing spaces, and any number of spaces between words all at once. You do not need to strip first or filter after.

Reverse: ["hello", "world"][::-1] gives ["world", "hello"].

Join: " ".join(["world", "hello"]) produces "world hello". One space between words, no leading or trailing spaces.

Now take "a good example". Split gives ["a", "good", "example"]. Three spaces between "good" and "example" do not matter because split() treats any run of whitespace as a single delimiter. Reverse gives ["example", "good", "a"]. Join gives "example good a".

Complexity analysis

Time: O(n). Splitting the string scans every character once. Reversing the word list is O(k) where k is the number of words, and k is at most n. Joining iterates through all characters again. Total work is proportional to the length of the input.

Space: O(n). The split operation creates a list of words, and the join operation creates a new string. Both require O(n) space in total.

For the in-place approach on a mutable character array, the space is O(1) beyond the input itself. In Python, since strings are immutable, you still need O(n) for the character list, so the practical space is the same.

ApproachTimeSpace
Split, reverse, joinO(n)O(n)
In-place reversal (mutable)O(n)O(1)

The building blocks

This problem decomposes into two reusable bricks that appear across many string problems.

String splitting

Splitting a string by a delimiter and handling edge cases (empty tokens, leading/trailing delimiters) is a fundamental operation. The same skill applies to parsing CSV data, tokenizing expressions, and many other string problems. In Python, knowing the difference between s.split(" ") (which preserves empty strings) and s.split() (which discards them) is important. This problem specifically requires the behavior of s.split().

Word reversal

Reversing a list of tokens, or reversing a portion of a string in-place, is a building block that shows up in problems like Rotate Array (reverse subarrays to achieve rotation) and Reverse String (the base case of in-place reversal). The double-reversal trick (reverse everything, then reverse each piece) is a pattern worth internalizing because it converts a position-shuffling problem into two simple reversals.

Edge cases

Leading and trailing spaces. " hello world " should return "world hello". The split-based approach handles this automatically. The in-place approach requires a cleanup pass to compact spaces.

Multiple spaces between words. "a good example" has three spaces between "good" and "example". After splitting (or after the in-place cleanup), only single spaces remain in the output.

Single word. " hello " should return "hello". There is only one word, so reversing the word list is a no-op. The spaces just get trimmed.

Already reversed / no change needed. "word" with no spaces at all returns "word". A single-element list reversed is itself.

The most common mistake is using s.split(" ") instead of s.split(). The former splits on each individual space and produces empty strings for consecutive spaces. The latter splits on any whitespace run and filters empty strings automatically. Know which one you need.

From understanding to recall

Reading the split-reverse-join solution feels obvious. It is three method calls. But try writing the in-place version from scratch in two weeks. The double-reversal trick, the space compaction logic, the write pointer tracking where clean characters go. These details fade quickly if you only read them once.

The building blocks here are small: splitting on whitespace, reversing a subarray, compacting with a write pointer. Each one takes a few minutes to drill. Once they are in long-term memory, assembling either solution for this problem becomes mechanical. You are not memorizing a specific LeetCode answer. You are internalizing techniques that also help with Rotate Array, Reverse String, and any problem involving token reordering.

Related posts

  • Valid Palindrome - Another string problem where handling whitespace and special characters is key
  • Rotate Array - Uses the same double-reversal technique to rotate elements in-place