Reverse Words in a String III (LeetCode 557): Solution and Explanation
You get a sentence whose words are separated by single spaces. Flip the letters of every word, keep the words in their original order, and keep each space where it was.
Intuition
Nothing moves between words. The first word stays first, the spaces stay at the same indices, and only the letters inside each word change places. So the problem breaks into many tiny, independent problems: reverse this run of characters, then the next one.
Reversing a run in place is the classic two-pointer swap. Put one pointer on the first letter and one on the last, swap them, step both inward, and stop when they meet or cross. Each swap fixes two letters at once.
Finding a run is just as simple. From the start of a word, walk forward until you hit a space or the end of the string. That index is one past the word's last letter, and the next word starts right after the space.
Put together, a single left-to-right pass visits every character a constant number of times: once while scanning for the end of its word and at most once in a swap.
Approach: Two pointers per word
- Copy
sinto a mutable character array and setstart = 0. - While
start < n, moveendforward fromstartuntilchars[end]is a space orend == n. - Set
left = startandright = end - 1. Whileleft < right, swapchars[left]andchars[right], thenleft += 1andright -= 1. - Set
start = end + 1to jump over the space to the next word. - Join the array back into a string and return it.
Step-by-step example
s = "Let's take LeetCode contest"
- start = 0. end walks to the space at index 5, so the first word is
Let'sat indices 0 to 4. - left = 0, right = 4: swap L and s. left = 1, right = 3: swap e and the apostrophe. The pointers meet at 2, so the word reads
s'teL. - start = 6. The word
takespans 6 to 9. Two swaps turn it intoekat. - start = 11.
LeetCodespans 11 to 18. Four swaps giveedoCteeL. - start = 20.
contestruns to the end of the string. Three swaps givetsetnoc, and the middle t stays put. - Joining the array gives
"s'teL ekat edoCteeL tsetnoc".
Code: Python, Java, C++
1class Solution:
2 def reverseWords(self, s: str) -> str:
3 chars = list(s)
4 n = len(chars)
5 start = 0
6 while start < n:
7 end = start
8 while end < n and chars[end] != ' ':
9 end += 1
10 left, right = start, end - 1
11 while left < right:
12 chars[left], chars[right] = chars[right], chars[left]
13 left += 1
14 right -= 1
15 start = end + 1
16 return ''.join(chars)1class Solution {
2 public String reverseWords(String s) {
3 char[] chars = s.toCharArray();
4 int n = chars.length;
5 int start = 0;
6 while (start < n) {
7 int end = start;
8 while (end < n && chars[end] != ' ') {
9 end++;
10 }
11 int left = start, right = end - 1;
12 while (left < right) {
13 char tmp = chars[left];
14 chars[left] = chars[right];
15 chars[right] = tmp;
16 left++;
17 right--;
18 }
19 start = end + 1;
20 }
21 return new String(chars);
22 }
23}1class Solution {
2public:
3 string reverseWords(string s) {
4 int n = s.size();
5 int start = 0;
6 while (start < n) {
7 int end = start;
8 while (end < n && s[end] != ' ') {
9 end++;
10 }
11 int left = start, right = end - 1;
12 while (left < right) {
13 swap(s[left], s[right]);
14 left++;
15 right--;
16 }
17 start = end + 1;
18 }
19 return s;
20 }
21};Time and space complexity
O(n)
The end scan touches each character once, and each character takes part in at most one swap, so the total work is linear in the length of s.
O(n)
Strings are immutable in Python, Java, JavaScript, C# and Go, so the solution copies them into an array. In C++ the string is reversed in place with O(1) extra space.
Other approaches
Split, reverse, join (time O(n), space O(n))
Split on spaces, reverse each word with a built-in (for example w[::-1] in Python), and join with single spaces. It is a one-liner and just as fast asymptotically, but it hides the mechanism and allocates a list of words plus a new string per word.
Reverse everything, then reverse the word order (time O(n), space O(n))
Reverse the whole string, which flips the letters and the word order, then reverse the order of the words back. It works but does twice the work and is easy to get wrong; it is the trick for Reverse Words in a String, not this problem.
Common mistakes
- Forgetting the last word. The last word has no space after it, so the scan must also stop at
end == n. - Using
right = endinstead ofend - 1.endpoints at the space (or past the string), not at the last letter. - Looping with
left <= right. Swapping a character with itself is harmless, but the conditionleft < rightmakes the intent clear and avoids an extra iteration. - Building the answer with repeated string concatenation in a loop, which can be quadratic in some languages. Work on an array and join once.
Frequently asked questions
Do I need to handle multiple spaces or leading spaces?
No. The constraints say words are separated by exactly one space and there are no leading or trailing spaces. The scan still works if there were extra spaces, because an empty run just has nothing to swap.
Why is the two-pointer reversal better than splitting the string?
Both are O(n) time. The two-pointer version works in place on one array and shows exactly how a reversal works, which interviewers usually want to see. The split version is fine when brevity matters more.
How is this different from Reverse Words in a String?
That problem reverses the order of the words and keeps each word's letters. This one keeps the word order and reverses the letters inside each word.
What is the time and space complexity?
O(n) time, since each character is scanned once and swapped at most once. Space is O(n) for the character array in languages with immutable strings, and O(1) extra in C++.