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
- Four words come back in the opposite order, and the doubled and edge spaces are gone.
"blue is sky the"
Example 2
- Input
- s = " a "
- Output
- One word, so the order cannot change, and the spaces at both ends are still dropped.
"a"
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
More like this
All strings examples (13) →- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.
- Caesar cipher Rotate each letter through the alphabet and wrap around.