Reverse Words in a String

Medium · Two Pointers · Explanation and code example

Split, Reverse, and Join

How it works

Split the input into words, reverse their order, and join them with one space. Splitting on whitespace removes leading and trailing spaces and collapses repeated spaces. Reverse the list of words, preserving the character order inside each word. The C++ example reads words with a string stream, which performs the same whitespace handling.

Steps

  1. Extract the nonempty words from the input.
  2. Reverse the word list.
  3. Join the words with exactly one space between adjacent words.
  4. Return the resulting string.

Complexity

For n input characters, time is O(n) and auxiliary space is O(n) for the words and output. This approach builds a new string.

Things to watch for

  • Split on whitespace rather than a literal single space so repeated spaces do not create empty words.
  • Reverse word order, keeping each word intact. For example, hello world becomes world hello.
  • Produce no leading or trailing space.

The explanation and C++ translation follow the linked NeetCode Python example.

Python code example

class Solution:
    def reverseWords(self, s: str) -> str:
        # Remove leading and trailing spaces
        s = s.strip()
        
        # Split the string into words
        words = s.split()
        
        # Reverse the order of words
        words = words[::-1]
        
        # Join the words with a single space
        reversed_str = ' '.join(words)
        
        return reversed_str

C++ code example

class Solution {
public:
    string reverseWords(string s) {
        istringstream input(s);
        vector<string> words;
        string word;
        while (input >> word) words.push_back(word);
        reverse(words.begin(), words.end());
        string result;
        for (const string& current : words) {
            if (!result.empty()) result += " ";
            result += current;
        }
        return result;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations