DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 151. Reverse Words in a String

Naive Approach

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    const arr = s.split(' ');
    const res = [];
    for(let i =0;i<arr.length;i++){
        let lastword = arr[arr.length-i-1];
        if(lastword != ''){
            res.push(lastword)
        }     
    }
    return res.join(' ')
};
Enter fullscreen mode Exit fullscreen mode

Time Complexity is O(n) as we are iterating through the words we splitted , (n is the words in string)
Space Complexity is O(n) as we are using res variable array to store

Using Regex

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function (s) {
  s = s.trim();
  s = s.replace(/\s+/g, " ");
  s = s.split(" ").reverse().join(" ");
  return s;
};
Enter fullscreen mode Exit fullscreen mode
  1. s.trim() will trim the spaces in the beginning and end
  2. /\s+/g , The regular expression \s+ matches one or more whitespace characters, and the g flag indicates a global replacement (i.e., it replaces all instances throughout the string)
  3. .reverse() reverses the order of the array elements , .join(" ") joins the array back into a single string with spaces between the words Without using Reverse and split methods
function reverseWords(s) {
  const ret = [];
  let word = [];
  for (let i = 0; i < s.length; ++i) {
    if (s.charAt(i) === ' ') {
        // We found the space, put word in front (if there is any)
        word.length > 0 && ret.unshift(word.join(''));
        // Reset the current word
        word = [];
      }
    else {
      // Add characters to the current word
      word.push(s.charAt(i));
    }
  }
  // If there is current word exists, add it in front
  word.length > 0 && ret.unshift(word.join(''));
  return ret.join(' ');
};
Enter fullscreen mode Exit fullscreen mode
  1. ret: An empty array that will store the words in reverse order.
  2. word: An empty array that temporarily holds characters of the current word being processed.
  3. If the current character is a space, it means the end of a word has been reached.
  4. word.length > 0 && ret.unshift(word.join(''));:
  5. word.length > 0 checks if word is not empty.
  6. word.join('') converts the word array (containing characters) into a string.
  7. ret.unshift(...) adds the word to the beginning of the ret array. This ensures that words are reversed in order.
  8. word = []; resets the word array to start collecting the next word.
  9. After the loop completes, there might be one last word in the word array that hasn't been added to ret.
  10. word.length > 0 && ret.unshift(word.join('')); adds this final word to the beginning of the ret array.

Top comments (0)