Reverse Words in a String
Given a string s, reverse the order of the words. A word is a sequence of non-space characters. Return the words in reverse order, separated by a single space.
The input may have leading/trailing spaces and multiple spaces between words. The output should have no extra spaces.
Examples
Input: s = "the sky is blue"
Output: "blue is sky the"
Input: s = " hello world "
Output: "world hello"
Input: s = "a good example"
Output: "example good a"
Constraints
1 <= s.length <= 10^4smay contain leading or trailing spaces and multiple spaces between words.
Sample Input
s = "the sky is blue"
Sample Output
"blue is sky the"
Constraints
- 1 <= s.length <= 10^4
- s contains English letters, digits, and spaces
Test Cases
Case 1
Args: ["the sky is blue"]
Expected: "blue is sky the"
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.