- The string us turned into an array.
- All the spaces in the array are removed in a loop.
- The words are the added into an array from the last to the first so that its in a reversed order.
- I use the join operator to add words together with single spaces
-
Time complexity: O(N)
-
Space complexity: O(N)
function reverseWords(s: string): string {
let strings = s.split(" ")
let reversedWords = []
let i = 0;
while (i <strings.length) {
let letters = strings[i]
if (letters.length !== 0) {
reversedWords.unshift(strings[i])
}
i++
}
return reversedWords.join(" ")
};