O(n) and Constant Space Solution


#1

module.exports = {
solve : function(s){

    let A = " " + s; 
    if(s.length == 1) return s;

      let ans = " ";
      let word = " ";
      let temp = "";
    
    for (let index = A.length - 1; index > 0; index--) {

            if (A[index] == " " && A[index - 1] == " ") {
            continue;
    }

    if (A[index] == " ") {
        ans += word + " ";
        word = "";
        continue;
    }

    if (word == " ") {
        word = A[index];
        temp = "";
    } else {
        temp = A[index];
        word = temp + word;
        temp = "";
    }
}
    ans += word;
    return ans.trim();

}

};