← All Lessons Lesson 25 / 68
Lesson 25

Reverse the Order of Words in a String

Reversing Word Order in a String

Imagine you have a sentence, and your task is to keep every word the same, but flip the order they appear in. The last word should come first, and the first word should come last. This is a very common text problem, and solving it teaches you how to break a sentence into pieces and put it back together.

What the problem asks

You are given a string s that contains some words. You must return a new string where the words appear in reverse order, with these rules:

  • Words are separated by a single space in the answer.
  • There must be no extra space at the start (no leading space).
  • There must be no extra space at the end (no trailing space).
  • Only one space sits between any two words, even if the input had many.

Here is the tricky part: the input is messy. The words might be separated by one space or several spaces. There could also be spaces at the beginning or the end. Your job is to clean all of that up.

A concrete example

Input:

This is a string

Output:

string a is This

The four words are This, is, a, and string. We simply read them from last to first: string, then a, then is, then This. We join them with a single space, and that gives the answer.

How to think about the solution

A clear, beginner-friendly plan has two steps:

  1. Split the sentence into words. Walk through the string and pull out each chunk of non-space characters. Skip over any spaces, no matter how many there are. This naturally throws away leading, trailing, and extra middle spaces. You now have a clean list of words.
  2. Build the answer in reverse. Start from the last word in your list and move toward the first. Add each word to the result. Put a single space between words, but not before the first one or after the last one.

A simple way to handle spacing correctly: add the first word with no space, and for every word after it, add a space and then the word. This guarantees exactly one space between words and none at the ends.

The code you fill in

The starter code gives you a function to complete:

using namespace std;
class Solution {
public:
    string reverseWordOrder(string s) {

    }
};

You receive the messy string s, and you return the cleaned, reversed string. The key insight is the same no matter the language: extract the words, then output them back-to-front, joined by single spaces.

Why this matters

This problem hides an important lesson: never trust input to be tidy. Real text is full of stray spaces. Good code separates the *meaningful* parts (the words) from the *noise* (the spaces) first, then does the actual work. Once your words are clean, reversing their order is easy.

Reverse the Order of Words in a String
Diagram — click to zoom (scroll / drag to pan)