Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

45. Reverse Words in a String

MediumDay 14 of 60Strings

Given a string s made of words separated by spaces, return a string with the words in reverse order, joined by single spaces. A word is any run of non-space characters. The input may have leading, trailing or repeated spaces between words, but the output must have none of them.

Example 1
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2
Input: s = " hello world "
Output: "world hello"
Leading and trailing spaces are dropped.
Constraints
  • 1 <= s.length <= 10^4
  • `s` contains English letters, digits and spaces
  • `s` has at least one word
Hints
Frequently asked at: Microsoft, Amazon, Qualcomm, Zoho, Wipro
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min