AlgoMaster Logo

Reverse Words in a String

Last Updated: April 2, 2026

medium
4 min read

Understanding the Problem

At first glance, this seems like a straightforward "split and reverse" problem. And in many languages, it almost is. But the problem has a few wrinkles that make it more interesting than it appears.

First, the input string can have leading spaces, trailing spaces, and multiple spaces between words. Your output must have exactly one space between each word and no extra spaces at the beginning or end. So you can't just reverse the entire string and call it a day, because the spaces would end up in the wrong places.

Second, the follow-up question asks whether you can solve it in O(1) extra space if the string is mutable. This is where the problem goes from "easy with built-ins" to "interesting algorithmic challenge." The key insight for the in-place approach is that reversing the entire string puts the words in the right order but each word is backwards, so you reverse each word individually to fix that.

Key Constraints:

  • 1 <= s.length <= 10^4 → With up to 10,000 characters, even an O(n^2) approach would work within time limits. But we should aim for O(n) since it's achievable and cleaner.
  • s contains letters, digits, and spaces → No special characters to worry about. A "word" is simply any contiguous sequence of non-space characters.
  • There is at least one word → We don't need to handle the empty result case.

Approach 1: Split and Reverse (Built-in Functions)

Intuition

The most natural first attempt is to lean on your language's built-in string operations. Split the string by spaces to get the individual words, filter out any empty strings that result from multiple consecutive spaces, reverse the list of words, and join them back together with a single space.

This is perfectly valid in an interview, especially as a starting point. Most interviewers will accept this and then ask you to implement it without using split/join, which leads us to Approach 2.

Algorithm

  1. Split the string s by spaces to get an array of tokens
  2. Filter out any empty strings from the array (caused by multiple consecutive spaces)
  3. Reverse the array of words
  4. Join the words with a single space and return the result

Example Walkthrough

1Start with s = "a good example"
0
a
1
,
2
g
3
o
4
o
5
d
6
,
7
,
8
,
9
e
10
x
11
a
12
m
13
p
14
l
15
e
1/4

Code

This approach relies on built-in split and join, which allocate extra space. What if we scanned the string ourselves to extract words directly, without using split at all?

Approach 2: Two Pointers (Reverse Traversal)

Intuition

Instead of relying on built-in split, we can scan the string from right to left and extract words manually. By traversing backwards, we naturally encounter words in reverse order, which is exactly what we need.

The idea is simple: use two pointers to find the boundaries of each word. Start from the end of the string, skip any trailing spaces, then find where the word begins. Extract that word and append it to the result. Repeat until you've processed the entire string.

This approach shows the interviewer you can work with string indices directly, and it's the typical "no built-ins" solution they're looking for.

Algorithm

  1. Initialize an empty result (StringBuilder or equivalent) and set pointer i to the last index of the string
  2. While i >= 0:
    • Skip spaces by decrementing i while s[i] is a space
    • If i < 0, break (we've processed everything)
    • Set end = i (this is the last character of the current word)
    • Move i left while s[i] is not a space and i >= 0 to find the start of the word
    • The word is s[i+1 ... end]
    • If the result is not empty, append a space before the word
    • Append the word to the result
  3. Return the result

Code

Both approaches so far use O(n) extra space for the result. What if we could rearrange the characters in place without creating a new string, by reversing the entire string first and then reversing each word individually?

Approach 3: Reverse Entire String, Then Reverse Each Word

Intuition

This is the approach that really impresses interviewers, especially when they ask the follow-up: "Can you do it in O(1) extra space if the string is mutable?"

The insight is beautifully simple. Consider the string "the sky is blue":

  1. Reverse the entire string: "eulb si yks eht"
  2. Now the words are in the correct order ("eulb" was "blue", "si" was "is", etc.), but each word is spelled backwards.
  3. Reverse each individual word: "blue is sky the"

That's it. Two passes, and you've reversed the word order while keeping each word intact.

The only complication is handling extra spaces. After reversing the entire string, extra spaces may appear in the wrong places. We handle this with a write pointer that compacts the string as we process each word.

Algorithm

  1. Convert the string to a mutable character array
  2. Reverse the entire character array
  3. Use a write pointer to process each word:
    • Skip leading spaces
    • If the write pointer is not at position 0, write a single space (word separator)
    • Copy the word characters to the write position
    • Reverse the word that was just written (to un-reverse it)
  4. Return the substring from index 0 to the write pointer

Code