Reverse Words in a String III(#557)

Category: String, Two Pointer

๐Ÿงฉ 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: Each word is reversed but the order of the words remains the same.

Input: s = "Hello World"

Output: "olleH dlroW"

Explanation: Each word is reversed in place.

Input: s = "a b c"

Output: "a b c"

Explanation: Single character words remain the same.

๐Ÿง  Approach

To reverse each word in a string while maintaining word order:

โ€ข **Split** the input string by spaces to get all the individual words.

โ€ข For each word, **reverse the characters** using a helper function that uses the two-pointer technique.

โ€ข In the helper function, convert the word to an array of characters, swap characters from both ends moving toward the center, then rejoin them.

โ€ข Finally, **join all reversed words** back into a single string with spaces.

This method ensures in-place reversal of each word without disturbing the original word order.

๐Ÿ’ป Code

var reverseWords = function(s) {
  let chars = s.split(" ");
  for (let i = 0; i < chars.length; i++) {
    chars[i] = reverseWord(chars[i]);
  }
  return chars.join(" ");
};

function reverseWord(word) {
  let start = 0, end = word.length - 1;
  let chars = word.split("");
  while (start < end) {
    [chars[start], chars[end]] = [chars[end], chars[start]];
    start++;
    end--;
  }
  return chars.join("");
}

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(n)

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources