Strings · 130Medium
Reverse Words in a String
Given a string s, reverse the order of the words. Words are separated by one or more spaces. The result must have single spaces between words and no leading or trailing space.
Constraints
- 1 <= s.length <= 10^4
- s contains English letters, digits and spaces, and has at least one word.
Examples
reverseWords("the sky is blue") -> "blue is sky the"
reverseWords(" hello world ") -> "world hello" // outer spaces stripped
reverseWords("a good example") -> "example good a" // space runs collapse
reverseWords("hello") -> "hello" // a lone word is unchanged
reverseWords(" a ") -> "a"
reverseWords("1 2 3") -> "3 2 1"Edge cases
- Leading and trailing spaces must be stripped.
- Multiple spaces between words collapse into one.
- Word ORDER reverses; the letters inside each word do not.
Show the target complexity (spoiler)
- Naive
- Splitting naively on a single space produces empty strings that must be filtered.
- Target
- O(n) time — split on runs of whitespace, reverse the list, and join with single spaces. (O(1) space in place: reverse the whole string, then each word.)
Solve it
By hand, in your editor. The runner checks answers and timing.
git clone https://github.com/sarmadkung/optimal-round cd optimal-round # open problems/15-strings/130-reverse-words-in-a-string.js ./practice c 130