Reverse Words in a String
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
sin 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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more two pointers problems
- 125Valid PalindromeEasysolve
- 26Remove Duplicates from Sorted ArrayEasysolve
- 283Move ZeroesEasysolve
- 88Merge Sorted ArrayEasysolve
- 27Remove ElementEasysolve
- 392Is SubsequenceEasysolve
- 167Two Sum II - Input Array Is SortedMediumsolve
- 153SumMediumsolve
- 11Container With Most WaterMediumsolve
- 80Remove Duplicates from Sorted Array IIMediumsolve
- 189Rotate ArrayMediumsolve
- 5Longest Palindromic SubstringMediumsolve
- 42Trapping Rain WaterHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.