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(' ')
};
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;
};
- s.trim() will trim the spaces in the beginning and end
- /\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)
- .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(' ');
};
- ret: An empty array that will store the words in reverse order.
- word: An empty array that temporarily holds characters of the current word being processed.
- If the current character is a space, it means the end of a word has been reached.
- word.length > 0 && ret.unshift(word.join(''));:
- word.length > 0 checks if word is not empty.
- word.join('') converts the word array (containing characters) into a string.
- ret.unshift(...) adds the word to the beginning of the ret array. This ensures that words are reversed in order.
- word = []; resets the word array to start collecting the next word.
- After the loop completes, there might be one last word in the word array that hasn't been added to ret.
- word.length > 0 && ret.unshift(word.join('')); adds this final word to the beginning of the ret array.
 

 
    
Top comments (0)