Explorer
Data Structures & Algorithms

Reverse each word individually within a sentence.

Problem Statement

Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Examples

Input: s = "Mr Ding"

Output: "rM gniD"

Explanation: Combining the input according to Reverse every word in a string logic yields "rM gniD".

Input: s = "Let's take LeetCode contest"

Output: "s'teL ekat edoCteeL tsetnoc"

Explanation: Combining the input according to Reverse every word in a string logic yields "s'teL ekat edoCteeL tsetnoc".

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: Notice that the word order must remain the same, but the characters inside each word must be reversed. šŸ’” Hint 2: Split the string by single space. šŸ’” Hint 3: Reverse characters within each word, then join back with space.

Editorial & Approach

Problem Overview & Intuition

Split the string by whitespace, reverse the characters in each individual word while keeping word positions intact, and join the result back together.

Step-by-Step Approach

  1. Split s by " ".
  2. Map each word to word.split("").reverse().join("").
  3. Join words with " ".
  4. Return result.

Optimal Implementation (JavaScript)

function reverseWordsInString(s) {
  return s
    .split(' ')
    .map((word) => word.split('').reverse().join(''))
    .join(' ');
}

Complexity Analysis

Time Complexity O(N) — single pass to reverse each word.
Space Complexity O(N) — memory for words and result.

Edge Cases & Corner Traps Handled

  • Single character word.
  • Palindromic word: unchanged.

Reverse every word in a string

Medium
Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example Scenarios
1Example 1
Input: s = "Mr Ding"
Output: "rM gniD"
Explanation:

Combining the input according to Reverse every word in a string logic yields "rM gniD".

2Example 2
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Explanation:

Combining the input according to Reverse every word in a string logic yields "s'teL ekat edoCteeL tsetnoc".

Editor
Loading Editor...
s =
"Let's take LeetCode contest"
Output:Click "Run" above to execute and verify your code here.
s'teL ekat edoCteeL tsetnoc