easyleetcodeNot Started

Reverse Words in a String III

A curated StudyFlow practice problem with comprehensive editorial and multi-language solutions.

Solve on leetcode
Lesson

Problem Statement

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Explanation: Each word is reversed individually while preserving spaces and word positions.

Example 2:

Input: s = "Mr Ding"
Output: "rM gniD"
Explanation: Each word is reversed individually.

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

What You'll Learn

Key principles and algorithmic techniques you will master from this problem:

  • Identify word boundaries in a single linear pass.
  • Reverse substring segments in-place without altering whitespace.
  • Handle the final word boundary smoothly.

Pattern Recognition Trigger

How to instantly recognize this algorithmic pattern when encountering unseen interview questions:

Signals to Look For:

  • Reversing components locally while retaining global token positions.
  • Transforming words in a sentence separated by single spaces.

Algorithmic Decision Tree:

  • Reversing components locally while retaining global token positions.
  • Transforming words in a sentence separated by single spaces.

Connected Patterns:

Reverse Words in a StringReverse StringReverse String II

1. Split, Reverse Each Word, and Join

Intuition

Split the sentence s by space into a list of word strings. Reverse each word string using two pointers or slicing. Join all reversed words with a single space delimiter.

When to apply: Basic functional formulation in modern languages.

Algorithm

  1. Split s by ' ' into word array words.
  2. For each word in words, reverse its characters.
  3. Join words with ' '.
  4. Return result.

Split, Reverse Each Word, and Join Trace

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [Let's, take]
Current operationSTEP 1 OF 6
Observation: Split input string s = "Let's take" by space delimiter ' '
Visual state
Values and pointers at this exact step
array
S
Let's
take
0
1
Variables at this step
Words
["Let's","take"]
Count
2
Check / comparison
s.split(' ') produces words array: ["Let's", "take"].
Decision / next transition
Extract words as separate string elements in an array.
Why this step matters

Observation: Split input string s = "Let's take" by space delimiter ' '.

Decision: Yields array ["Let's", "take"] of length 2.

Invariant: Preserves original word ordering.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <vector>
4#include <sstream>
5#include <algorithm>
6
7class Solution {
8public:
9 std::string reverseWords(std::string s) {
10 std::stringstream ss(s);
11 std::string word;
12 std::string res = "";
13 while (ss >> word) {
14 std::reverse(word.begin(), word.end());
15 if (!res.empty()) res += " ";
16 res += word;
17 }
18 return res;
19 }
20};
21
22int main() {
23 Solution sol;
24 std::cout << sol.reverseWords("Let's take LeetCode contest") << std::endl; // "s'teL ekat edoCteeL tsetnoc"
25 std::cout << sol.reverseWords("Mr Ding") << std::endl; // "rM gniD"
26 return 0;
27}

Time & Space Complexity

  • Time complexity: O(N) — Splits and joins N characters across new string allocations.
  • Space complexity: O(N)

Why Brute Force Doesn't Scale:

In-place two-pointer reversal avoids intermediate substring allocations.

Operates with O(1) auxiliary variables.


2. String Builder Word Accumulator

Intuition

Maintain a character accumulator word. When a space is seen, reverse word, append it to res with a space, and clear word. At the end of string, reverse and append the final word.

When to apply: When streaming characters one by one without full-sentence splitting.

Algorithm

  1. Initialize res = "", word = "".
  2. For c in s:
  3. If c != ' ': word += c.
  4. Else:
  5. reverse(word)
  6. res += word + ' '
  7. word = ""
  8. Reverse and append final word.
  9. Return res.

String Builder Word Accumulator Trace

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [L, e, t, ', s, , t, a, k, e]
Current operationSTEP 1 OF 6
Observation: Iterate through s character by character
Visual state
Values and pointers at this exact step
array
S
L
e
t
'
s
0
1
2
3
4
↑ ACCUMULATE
Variables at this step
Buffer
Let's
Length
5
Check / comparison
Scan s[0..4]. Collect characters of first word into buffer: ['L', 'e', 't', ''', 's'].
Decision / next transition
Buffer accumulates word characters until space is encountered.
Why this step matters

Observation: Iterate through s character by character. Push characters into word buffer until space is encountered.

Decision: Buffer holds ['L', 'e', 't', ''', 's'].

Invariant: Characters accumulated in forward order.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5class Solution {
6public:
7 std::string reverseWords(std::string s) {
8 std::string res = "";
9 std::string word = "";
10 for (char c : s) {
11 if (c != ' ') {
12 word += c;
13 } else {
14 std::reverse(word.begin(), word.end());
15 res += word + " ";
16 word = "";
17 }
18 }
19 std::reverse(word.begin(), word.end());
20 res += word;
21 return res;
22 }
23};
24
25int main() {
26 Solution sol;
27 std::cout << sol.reverseWords("Let's take LeetCode contest") << std::endl; // "s'teL ekat edoCteeL tsetnoc"
28 return 0;
29}

Time & Space Complexity

  • Time complexity: O(N) — Each character is appended and reversed in O(1) amortized time.
  • Space complexity: O(N)

3. Two Pointers In-Place Single Pass (Optimal)

Intuition

Maintain start = 0. Iterate i from 0 to s.length: when i == s.length || s[i] == ' ', reverse the characters between start and i - 1 in-place using two converging pointers, then set start = i + 1.

When to apply: The standard gold standard solution for minimal memory and single pass performance.

Algorithm

  1. Initialize start = 0, n = s.length.
  2. For i from 0 to n:
  3. If i == n || s[i] == ' ':
  4. Reverse s from index start to i - 1.
  5. start = i + 1.
  6. Return s.

Space-Delimited Segmental In-Place Reversal

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [L, e, t, ', s, , t, a, k, e]
Current operationSTEP 1 OF 6
Observation: Pointers identify first word bounds: left = 0 ('L') and right = 4 ('s') right before space at index 5
Visual state
Values and pointers at this exact step
array
S
L
e
t
'
s
t
a
k
e
0
↑ L=0
1
2
3
4
↑ R=4
5
6
7
8
9
Variables at this step
Word
Let's
L Pointer
0 ('L')
R Pointer
4 ('s')
Action
Swap 'L' <-> 's'
Check / comparison
First word "Let's" spans indices 0..4. Swap s[0] ('L') with s[4] ('s').
Decision / next transition
Initiate two-pointer reversal on first word.
Why this step matters

Observation: Pointers identify first word bounds: left = 0 (L) and right = 4 (s) right before space at index 5.

Decision: Initialize two-pointer reversal on the identified word segment [0, 4].

Invariant: Individual word characters will be swapped symmetrically while space delimiters stay intact.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5class Solution {
6 void reverseRange(std::string& s, int l, int r) {
7 while (l < r) {
8 std::swap(s[l++], s[r--]);
9 }
10 }
11public:
12 std::string reverseWords(std::string s) {
13 int n = s.size();
14 int start = 0;
15 for (int i = 0; i <= n; ++i) {
16 if (i == n || s[i] == ' ') {
17 reverseRange(s, start, i - 1);
18 start = i + 1;
19 }
20 }
21 return s;
22 }
23};
24
25int main() {
26 Solution sol;
27 std::cout << sol.reverseWords("Let's take LeetCode contest") << std::endl; // "s'teL ekat edoCteeL tsetnoc"
28 std::cout << sol.reverseWords("Mr Ding") << std::endl; // "rM gniD"
29 return 0;
30}

Time & Space Complexity

  • Time complexity: O(N) strictly — Every character is visited once and swapped at most once in a single pass.
  • Space complexity: O(1) extra space (in C++) / O(N) (in Java/JS/Python)

Approach Comparison Matrix

Side-by-side comparison of time, space, and algorithmic trade-offs across each approach:

ApproachTimeSpaceCore IdeaTrade-off / Bottleneck
1.Split Words and Reverse IndividuallyO(N)O(N)Simple high-level functional code.Allocates array of word strings.
2.Two Pointers In-Place Single Pass (Optimal)OptimalO(N)O(1) extra spaceZero extra memory in mutable strings, single forward sweep.Requires character array mutation in JS/Python/Java.

Common Pitfalls & Crucial Edge Cases

Pitfall 1:

Stopping the loop at i < n and forgetting to reverse the final word.

Pitfall 2:

Modifying spaces or introducing extra spaces between words.

Crucial Edge Cases to Validate:

  • Single word without spaces (s = Hello): Reverses range from start=0 to n-1, returning olleH.
  • Words of length 1 (s = 'a b c'): reverseRange(start, start) leaves single characters unchanged, returning 'a b c'.
  • Special characters and punctuation (s = "Let's"): Punctuation is treated as normal characters, producing "s'teL".

Interview Tips & Best Practices

How to communicate your thought process and address follow-ups in a live technical interview:

  1. Note the contrast with Reverse Words in a String I: word order is preserved while characters are reversed.
  2. Explain the i <= n loop boundary trick for clean handling of the last word.

Quick Comprehension Check

Test your intuitive understanding of the core concept in 30 seconds:

1.Why does looping to i <= n simplify word boundary handling?