Reverse Words in a String

Reverse the order of whitespace-delimited words, collapsing extra spaces.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
two-pointers string

Problem#

Reverse the order of words in s. Words are sequences of non-space chars separated by one or more spaces. Strip leading/trailing spaces and collapse internal multi-spaces to single spaces.

Examples#

  • "the sky is blue""blue is sky the"
  • " hello world ""world hello"
  • "a good example""example good a"

Constraints#

  • 1 <= s.length <= 10^4, ASCII letters/digits/spaces, at least one word.

Hints#

Hint 1
Reverse the whole string, then reverse each word in place.
Hint 2
A write-pointer compacts the spaces in a second linear pass.

Approach#

Two-stage in-place: (1) trim and collapse spaces using a write pointer; (2) reverse the whole string, then reverse each word individually. Net result: words appear in reverse order with single-space separation.

Solution#

Reverse Words
class Solution {
public:
string reverseWords(string s) {
// 1) compact: trim + collapse internal spaces
int w = 0, i = 0, n = s.size();
while (i < n) {
while (i < n && s[i] == ' ') ++i;
if (i == n) break;
if (w > 0) s[w++] = ' ';
while (i < n && s[i] != ' ') s[w++] = s[i++];
}
s.resize(w);
// 2) reverse all, then reverse each word
reverse(s.begin(), s.end());
int start = 0;
for (int j = 0; j <= (int)s.size(); ++j) {
if (j == (int)s.size() || s[j] == ' ') {
reverse(s.begin() + start, s.begin() + j);
start = j + 1;
}
}
return s;
}
};

Editorial#

The trick is decoupling “rearrange words” from “normalize whitespace”. Doing them in one pass tangles the indices; doing whitespace normalization first means the second stage operates on a clean canonical form, and “reverse all then re-reverse each word” is the canonical idiom for in-place word-order reversal — both operations are O(n) and need no extra buffer.

Complexity#

  • Time: O(n).
  • Space: O(1) extra (output reuses the input string).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.