Reverse Words in a String

Medium#151from the right end

You get a string of words separated by spaces. Return the same words in reverse order, with exactly one space between them and none at the start or the end — even if the string has extra spaces there or between the words. Our example: "␣red␣␣fox␣", where ␣ is a space — the answer is "fox red".

input
s: words of letters and digits with spaces between them, maybe several, and maybe at the ends.
returns
The words of s in reverse order, one space between them and none at the ends.
constraints
  • 1 ≤ s.length ≤ 10⁴
  • s: English letters, digits and spaces
  • s has at least one word
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} s
 * @return {string}
 */
function reverseWords(s) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.