A clear explanation of Reverse Words in a String III using two-pointer scanning and string reversal.
Problem Restatement
We are given a string s.
The string contains words separated by single spaces.
We need to reverse the characters inside each word while keeping:
- The word order unchanged.
- The spaces in the same positions.
The problem guarantees there are no leading or trailing spaces, and words are separated by exactly one space. (github.com)
Input and Output
| Item | Meaning |
|---|---|
| Input | A string s |
| Output | A string with each word reversed |
| Keep unchanged | Word order |
| Keep unchanged | Space positions |
Example function shape:
def reverseWords(s: str) -> str:
...Examples
Example 1:
s = "Let's take LeetCode contest"Reverse each word individually:
| Original | Reversed |
|---|---|
"Let's" | "s'teL" |
"take" | "ekat" |
"LeetCode" | "edoCteeL" |
"contest" | "tsetnoc" |
The final answer is:
"s'teL ekat edoCteeL tsetnoc"Example 2:
s = "God Ding"Reverse each word:
"doG gniD"First Thought: Split Into Words
The most direct idea is:
- Split the string by spaces.
- Reverse every word.
- Join the words back together with spaces.
For example:
s.split()turns:
"God Ding"into:
["God", "Ding"]Then we reverse each word and join them again.
This solution is already efficient enough for the problem constraints.
Key Insight
We do not need to change the structure of the sentence.
Only the characters inside each word need to be reversed.
The spaces remain fixed.
So each word can be processed independently.
Algorithm
- Split the string into words.
- Reverse every word using slicing:
word[::-1] - Join the reversed words using spaces.
Correctness
The algorithm processes every word independently.
For each word, the expression:
word[::-1]returns the characters of the word in reverse order.
The list of words remains in the original order because the algorithm never reorders the words themselves.
Finally, joining the reversed words using single spaces reconstructs the sentence with exactly one space between adjacent words.
Therefore:
- Every word is reversed correctly.
- The word order is preserved.
- The spacing structure is preserved.
So the algorithm produces exactly the required output.
Complexity
Let n be the length of s.
| Metric | Value | Why |
|---|---|---|
| Time | O(n) | Every character is processed a constant number of times |
| Space | O(n) | The output string and temporary word list require linear space |
Implementation
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(word[::-1] for word in s.split())Code Explanation
We first split the sentence into words:
s.split()Then we reverse every word:
word[::-1]The slice syntax with step -1 walks through the string backward.
Finally:
" ".join(...)joins the reversed words back into one sentence using spaces.
Two-Pointer Version
We can also solve the problem manually without using split().
This version scans the string directly.
class Solution:
def reverseWords(self, s: str) -> str:
chars = list(s)
n = len(chars)
start = 0
for end in range(n + 1):
if end == n or chars[end] == " ":
left = start
right = end - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
start = end + 1
return "".join(chars)This version reverses each word in place inside the character array.
Testing
def run_tests():
s = Solution()
assert s.reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc"
assert s.reverseWords("God Ding") == "doG gniD"
assert s.reverseWords("a") == "a"
assert s.reverseWords("ab cd") == "ba dc"
assert s.reverseWords("Python") == "nohtyP"
print("all tests passed")
run_tests()| Test | Why |
|---|---|
"Let's take LeetCode contest" | Official-style example |
"God Ding" | Multiple short words |
"a" | Single-character word |
"ab cd" | Two small words |
"Python" | Single full-word input |