Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

How do you reverse the order of words in a sentence, ignoring extra spaces?

SHORT ANSWER

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

js
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: hello

Complexity

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.

#strings

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.