← All problems

6. Reverse Words in a String

MediumArray / StringOriginal on LeetCode ↗

A word is a run of non-space characters. Return the words of s in reverse order, joined by exactly one space.

s may have spaces at the start or end, or several spaces between two words. None of that extra spacing should appear in the result.

Constraints

  • 1 <= len(s) <= 10000
  • s has English letters, digits and spaces, and at least one word.

Examples

Example 1
Input:  s = "practice makes progress"
Output: "progress makes practice"
Example 2
Input:  s = "   leading and trailing  "
Output: "trailing and leading"
Example 3
Input:  s = "one   two  three"
Output: "three two one"

Hints

Hint 1

Python's str.split() with no argument already drops extra spaces.

Hint 2

Try it without split as well: scan from the right and collect each word.

Python 3

Run checks the examples · Submit checks every test. The first run downloads Python (about 10 MB) and takes a few seconds.