What does it solve?
Reverse the order of words in a sentence (trimming extra spaces). "the sky is blue" → "blue is sky the". The elegant in-place approach uses the two-pointer reversal trick twice.
Key insight: reverse the entire character array with two pointers closing from both ends, which flips word order but scrambles each word's letters. Then reverse each individual word back to fix the letters. Two linear passes of the same swap primitive → O(N).
The core idea
reverse(s, i, j):
while i < j: swap(s[i++], s[j--])
// 1) reverse whole 2) reverse each word
reverse(s, 0, n-1)
for each word span [a,b]: reverse(s, a, b)
Complexity
Two passes over the characters: one full reverse, one word-by-word reverse. Every character is swapped at most twice.
In-place with a char array (ignoring output). The naive split-and-join is O(N) extra space.
Examples & edge cases
Step-by-step table
| Step | phase | i | j | swap | string |
|---|
C++ implementation
#include <bits/stdc++.h> using namespace std; // Two-pointer reverse of s[i..j] in place void rev(string& s, int i, int j) { while (i < j) swap(s[i++], s[j--]); } string reverseWords(string s) { // (optional) trim & collapse spaces first in practice int n = s.size(); rev(s, 0, n - 1); // 1) reverse the whole string int i = 0; while (i < n) { // 2) reverse each word back if (s[i] == ' ') { i++; continue; } int j = i; while (j < n && s[j] != ' ') j++; rev(s, i, j - 1); i = j; } return s; } int main() { cout << reverseWords("the sky is blue") << "\n"; // blue is sky the return 0; }
My Notes
📝Notes✅
Practice this problem