Reverse the words in a string

Medium TimeO(n) SpaceO(n)

Given a string s holding words separated by spaces, return its words in the opposite order, joined by a single space. The input may carry spaces at either end and more than one between words; the answer must have exactly one space between words and none at either end. The characters inside a word keep their own order — only the order of the words changes.

Examples

Example 1

Input
s = " the sky is blue "
Output
"blue is sky the"
Four words come back in the opposite order, and the doubled and edge spaces are gone.

Example 2

Input
s = " a "
Output
"a"
One word, so the order cannot change, and the spaces at both ends are still dropped.

The Code

function reverseWords(s) {
  const words = s.trim().split(/\s+/);
  const out = [];
  for (let i = words.length - 1; i >= 0; i--) {
    out.push(words[i]);
  }
  return out.join(" ");
}
reverseWords("  the sky   is blue  ");
Done
Step through reverseWords(" the sky is blue ") call by call