Reverse Words in a String

Medium

Description

Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. Return a string of the words in reverse order concatenated by a single space.

Examples

Input:s = "the sky is blue"
Output:"blue is sky the"
Explanation:

Words reversed.

Input:s = "programming is fun"
Output:"fun is programming"
Explanation:

The three words are reversed in order: 'programming' becomes last, 'is' stays in the middle, and 'fun' becomes first.

Input:s = " single "
Output:"single"
Explanation:

Even though there are multiple leading and trailing spaces, there is only one word 'single', so the output is just that word with no extra spaces.

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s contains English letters (upper and lower case), digits, and spaces.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!