Reverse each word individually within a sentence.
Problem Statement
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
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
- Split
sby" ". - Map each word to
word.split("").reverse().join(""). - Join words with
" ". - Return result.
Optimal Implementation (JavaScript)
function reverseWordsInString(s) {
return s
.split(' ')
.map((word) => word.split('').reverse().join(''))
.join(' ');
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single character word.
- Palindromic word: unchanged.