FrontendPro

11Reverse words in a sentence

easyAbout 15 minutesCodingstringstwo-pointers

Problem

Implement reverseWords(s). It returns the words of the sentence in reverse order, joined by a single space. A word is a run of non-space characters.

reverseWords("the sky is blue"); // "blue is sky the"
reverseWords("  hello world  "); // "world hello"
reverseWords("a good   example"); // "example good a"

Requirements

  • Remove leading and trailing spaces.
  • Collapse several spaces between words into one.
  • Keep each word itself unchanged, including punctuation.
  • Solve it in O(n) time.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

Reverse Words in a String - LeetCode 151 - Python #leetcode75Deepti Talesra on YouTubeOpen on YouTube

Step-by-step

s.trim().split(/\s+/).reverse().join(" ") is correct for most inputs and worth mentioning. Interviewers then usually ask you to do it without split and reverse, so be ready to scan by hand.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever