LeetCode / Classic Two Pointers · Reverse Medium

Reverse Words in a String

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

Reverse the whole string, then reverse each word back: two passes of a two-pointer swap put words in reverse order — O(N) time

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

// two-pointer reverse primitive
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

Time complexity
O(N)

Two passes over the characters: one full reverse, one word-by-word reverse. Every character is swapped at most twice.

Space complexity
O(1)

In-place with a char array (ignoring output). The naive split-and-join is O(N) extra space.


Examples & edge cases

Live animation — reverse the whole string
left pointer right pointer swapped/settled space
Character array
current
Current step detail
i = — j = — span = — swaps = —
Step — of —
left i
—
char
right j
—
char
reversing span
—
[a..b]
swaps done
—
so far
Select an example and press Play to start.
✓ Done
SpeedMedium

Step-by-step table

Stepphaseijswapstring

C++ implementation

reverse_words.cpp
#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