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
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--)
Step-by-step table
| # | Phase | lo | hi | Action | Words state |
|---|
C++ implementation
#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
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.
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