Community Problem

Reverse Words in a String III

Difficulty: Easy

Reverse the characters of every word in a sentence while keeping the word order intact.

Reverse Words in a String III

Reverse the characters of every word in a sentence while keeping the word order intact.

EASY
Free
strings
two-pointers
meinakamura

By @meinakamura

March 5, 2026

·

Updated May 18, 2026

765 views

7

4.3 (11)

Asked this on a phone screen last quarter and the candidate immediately reached for s.split(' ') plus a list comprehension. Works, but it costs O(n) extra space. The interesting variant is the in-place pass: walk the array, find each word's bounds, reverse that slice, repeat. Same O(n) time as the split approach, but O(1) extra space. Worth practicing because real interviewers love asking for the constant-space version after the easy answer.

Reverse Words in a String III

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and the initial word order. Words are separated by single spaces, and the string contains no leading or trailing spaces.

Examples

Example 1:

  • Input: s = "Let's take LeetCode contest"
  • Output: "s'teL ekat edoCteeL tsetnoc"
  • Explanation: Each word is reversed individually, the spaces between words stay in place.

Example 2:

  • Input: s = "Mr Ding"
  • Output: "rM gniD"
  • Explanation: Two words reversed, the single space preserved.

Example 3:

  • Input: s = "a"
  • Output: "a"
  • Explanation: Single character, single word; reversal of a one-character word is a no-op.

Example 4:

  • Input: s = "hello"
  • Output: "olleh"
  • Explanation: One word, reversed.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • All words are separated by a single space.

Follow-up

Can you do it in O(1) extra space? (Easier in C++ where strings are mutable; in JS / Python you can still hit O(1) auxiliary space if you track word bounds without allocating intermediate arrays.)

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems