1 minute read

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

Example 1:

Input: s = “Let’s take LeetCode contest” Output: “s’teL ekat edoCteeL tsetnoc” Example 2:

Input: s = “Mr Ding” Output: “rM gniD”

Constraints:

1 <= s.length <= 5 * 104 s contains printable ASCII characters. s does not contain any leading or trailing spaces. There is at least one word in s. All the words in s are separated by a single space.

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function (s) {
  // Split the input string 's' into an array of words using space as the delimiter
  let wordsArr = s.split(" ");

  // Iterate through each word in the array
  for (let i = 0; i < wordsArr.length; i++) {
    // Initialize two pointers 'left' and 'right' for reversing characters within the current word
    let left = 0;
    let right = wordsArr[i].length - 1;

    // Convert the current word into an array of characters
    let word = wordsArr[i].split("");

    // Use a while loop to reverse the characters in the current word
    while (left < right) {
      // Swap characters at 'left' and 'right' positions using a temporary variable
      let temp = word[left];
      word[left] = word[right];
      word[right] = temp;

      // Increment 'left' and decrement 'right' pointers
      left++;
      right--;
    }

    // Join the reversed characters back into a word and update the original array
    wordsArr[i] = word.join("");
  }

  // Join the modified array of words back into a string using space as the delimiter and return the result
  return wordsArr.join(" ");
};

Spliting the string of time complexity is O(n) and reversing the characters in each word is O(n/2) -> in this case, the division by 2 is dropped. Therefore, The overall time complexity is O(n) x O(m) = O(n x m).

Since I created an new array of words, the space complexity is O(n) where n is the length of the input string.

Leave a comment