Reverse Words in a String III

Easy

Topics
StringTwo Pointers

Given a string s of words separated by single spaces, reverse the characters of each word while preserving word order and spacing.

Example 1

inLetscode
outsteLedoc
The mirror image of the previous problem: each word is reversed in place while the word order and the spacing stay exactly as they were.
Chips are the words before and after.
Input:  s = "Lets code"
Output: "steL edoc"

Example 2

inGodDing
outdoGgniD
Input:  s = "God Ding"
Output: "doG gniD"

Constraints

  • 1 <= s.length <= 5*10^4
  • Words are separated by single spaces with no leading/trailing spaces.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each word is reversed where it sits; the word order and the spacing are untouched. So split on spaces, reverse each token, and join back. Because the constraints promise single spaces with no leading or trailing whitespace, the split-and-join round trip reproduces the original layout exactly.

The in-place alternative, which is what to offer if asked for O(1) extra space: scan for word boundaries and reverse each span with two pointers, on a mutable character buffer. Same O(n) time, no allocation beyond the buffer.

Approach

  1. Split on a single space.
  2. Reverse each token.
  3. Join with a single space.

Dry Run

s = "Let's take LeetCode contest"

tokens   ["Let's", "take", "LeetCode", "contest"]
reversed ["s'teL", "ekat", "edoCteeL", "tsetnoc"]
joined   "s'teL ekat edoCteeL tsetnoc"

Complexity

  • Time — O(n): every character is visited a constant number of times across the split, the reversals and the join.
  • Space — O(n): the token list and the output string. The two-pointer in-place version is O(1) beyond a mutable buffer, and is the better answer when space is the question.

Common Pitfalls

  • Splitting on whitespace generally rather than on a single space. split() with no argument collapses runs and drops empty tokens, which would alter the spacing if the input ever had any — here the constraints forbid it, so both happen to work.
  • Reversing the word order as well. That is a different problem; here only the letters within each word move.
  • Joining with the wrong separator, or using join on a generator twice.
  • Claiming O(1) space for the split version.

Full Solution — all languages

class Solution:
    def reverseWords(self, s):
        return " ".join(w[::-1] for w in s.split(" "))
SensAI
Beta
Tap the mic to stop voice mode