Code Logo

Reverse Words in String III

Published at25 Jul 2026
Medium 0 views
Like0

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and the order of words. A word is defined as a sequence of non-space characters.

Split the string into words by spaces. For each word, reverse its characters. Join the reversed words back with spaces. The reversal of each word is done individually, not the entire string.

Time complexity is O(n) where n is the string length. Each character is visited twice: once during splitting and once during reversal. Space is O(n) for the word array and result.

Example Input & Output

Example 1
Input
"abc"
Output
"cba"
Explanation

Single word reversed

Example 2
Input
""
Output
""
Explanation

Empty

Example 3
Input
"hello world"
Output
"olleh dlrow"
Explanation

Two words reversed

Example 4
Input
"the sky is blue"
Output
"eht yks si eulb"
Explanation

Each word reversed

Example 5
Input
"a b c"
Output
"a b c"
Explanation

Single chars unchanged

Algorithm Flow

Recommendation Algorithm Flow for Reverse Words in String III
Recommendation Algorithm Flow for Reverse Words in String III

Solution Approach

function solution(s) {
  return s.split(' ').map(function(w) {
    return w.split('').reverse().join('');
  }).join(' ');
}

Best Answers

java
class Solution {
    public String solution(String s) {
        String[] w=s.split(" ",-1);StringBuilder r=new StringBuilder();
        for(int i=0;i<w.length;i++){r.append(new StringBuilder(w[i]).reverse());if(i<w.length-1)r.append(' ');}
        return r.toString();
    }
}