String

Reverse Words in a String

LC
Practice this algorithm on LeetCode to reinforce your understanding.
Open Problem

Trim spaces, split into words, reverse the word order — O(n) time · O(n) space · LeetCode #151

What does it solve?

Given a string s with words separated by spaces (possibly multiple), return the words in reversed order separated by a single space — no leading or trailing spaces in the output.

The algorithm works in three clean phases: trim outer spaces, split into a word list, then reverse the list with two pointers swapping from the outside in.

The three-phase approach

// Phase 1: strip leading/trailing spaces
s = trim(s)
// Phase 2: split on whitespace runs
words = split(s)
// Phase 3: two-pointer word reverse
lo=0, hi=words.size()-1
while lo < hi: swap(lo++, hi--)
▶ Visualiser
Trimmed (removed)
Scanning / split
Swapping
Placed / settled
Final result
Input string
—
Output string
—
Words
Step — of —
Phase
—
—
lo pointer
—
left boundary
hi pointer
—
right boundary
Words found
—
total
Select an example and press Play to start.
✓ Reversed
Speed Medium

Step-by-step table

# Phase lo hi Action Words state

C++ implementation

reverse_words.cpp
#include <bits/stdc++.h>
using namespace std;

string reverseWords(string s) {
    // Phase 1: trim leading & trailing spaces
    int l = 0, r = s.size() - 1;
    while (l <= r && s[l] == ' ') l++;
    while (r >= l && s[r] == ' ') r--;
    s = s.substr(l, r - l + 1);

    // Phase 2: split on runs of whitespace
    vector<string> words;
    istringstream iss(s);
    string word;
    while (iss >> word) words.push_back(word);

    // Phase 3: reverse word list with two pointers
    int lo = 0, hi = words.size() - 1;
    while (lo < hi) {
        swap(words[lo], words[hi]);
        lo++; hi--;
    }

    // join with single spaces
    string res;
    for (int i = 0; i < words.size(); i++) {
        if (i) res += ' ';
        res += words[i];
    }
    return res;
}

int main() {
    cout << reverseWords("the sky is blue") << "\n";
    // output: "blue is sky the"
    return 0;
}

Complexity

Time complexity
O(n)

Each character is visited once in trim, once in split, and each word is touched once in the two-pointer reverse. All three phases are linear in the length of the input string.

Space complexity
O(n)

The words vector stores at most n characters in total. An in-place O(1) variant exists — reverse the whole string character-by-character, then reverse each word individually.

My Notes

📝 Notes ✅

▼
===== -->