How do you reverse the order of words in a sentence, ignoring extra spaces?
Trim the string, split on one or more whitespace characters, reverse the array of words, and join with a single space.
Explain it simply
Reversing a sentence word by word is like reading a train announcement backwards by phrase, not by letter. "the sky is blue" becomes "blue is sky the".
The catch is messy input: leading spaces, trailing spaces, and several spaces between words. Splitting on a regular expression for any run of whitespace handles all of those at once.
Example
function reverseWords(s) {
return s.trim().split(/\s+/).reverse().join(" ");
}
console.log(reverseWords(" the sky is blue ")); // Output: blue is sky the
console.log(reverseWords("hello")); // Output: helloComplexity
Time O(n), space O(n).
What to say in the interview
"I trim the string, split on the regex for one or more spaces so extra spaces vanish, reverse the array and join with a single space. Time and space are both O(n). If the interviewer wants O(1) extra space in a mutable language, I reverse the whole character array and then reverse each word."
Common mistakes
- Using split(" "), which leaves empty strings when there are repeated spaces.
- Reversing the letters of each word instead of the order of words.