Reverse Words in a String III

(#557), Easy

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

Split and Reverse Each Word

  • Split the input string by spaces to isolate words.
  • For each word, reverse its characters using a two-pointer approach.
  • Use a helper function that converts the word to an array, swaps characters from both ends, and joins it back.
  • Join the reversed words using spaces to reconstruct the sentence.
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