Reverse Words in a String III (LeetCode 557): Solution and Explanation

Easy
Two Pointers
String

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

  1. Copy s into a mutable character array and set start = 0.
  2. While start < n, move end forward from start until chars[end] is a space or end == n.
  3. Set left = start and right = end - 1. While left < right, swap chars[left] and chars[right], then left += 1 and right -= 1.
  4. Set start = end + 1 to jump over the space to the next word.
  5. Join the array back into a string and return it.

Step-by-step example

s = "Let's take LeetCode contest"
  1. start = 0. end walks to the space at index 5, so the first word is Let's at indices 0 to 4.
  2. 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.
  3. start = 6. The word take spans 6 to 9. Two swaps turn it into ekat.
  4. start = 11. LeetCode spans 11 to 18. Four swaps give edoCteeL.
  5. start = 20. contest runs to the end of the string. Three swaps give tsetnoc, and the middle t stays put.
  6. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 = end instead of end - 1. end points 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 condition left < right makes 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++.