Reverse Words in a String
You're given a string s made up of words โ where a word is any run of non-space characters โ separated by spaces. Produce a string containing those words in reverse order, with exactly one space between consecutive words.
Because the input can have leading or trailing spaces and runs of multiple spaces between words, make sure none of that extra spacing survives into the output.
Input Format
Implement reverseWords(s). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
s = "the sky is blue" Output
"blue is sky the" Example 2
Input
s = " hello world " Output
"world hello" Constraints
- 1 <= s.length <= 10^4
- s contains English letters, digits, and spaces
Test Cases (2)
Case 1
Args: ["the sky is blue"]
Expected: "blue is sky the"
Case 2
Args: [" hello world "]
Expected: "world hello"
Topics
Trim the string, split on one or more whitespace characters to extract words, reverse the array, and join with a single space. The regex split handles multiple consecutive spaces cleanly.
function reverseWords(s) {
return s.trim().split(/\s+/).reverse().join(' ');
}For a more manual approach without built-in reverse:
function reverseWords(s) {
const words = [];
let i = 0;
while (i < s.length) {
while (i < s.length && s[i] === ' ') i++;
if (i >= s.length) break;
let j = i;
while (j < s.length && s[j] !== ' ') j++;
words.push(s.substring(i, j));
i = j;
}
let left = 0, right = words.length - 1;
while (left < right) {
[words[left], words[right]] = [words[right], words[left]];
left++;
right--;
}
return words.join(' ');
}Time: O(n) โ one pass to split, one to reverse. Space: O(n) for the words array.
Saved in this browser only. Private to you.