iq.lab
Python starts when a code cell comes near or you run one
mediumLoops and basics target 25 min

Reverse the words

A string s is made of English letters, digits and spaces. A word is a stretch of letters and digits side by side, with a space or an end of s on each side. Spaces can sit between words, at the start, at the end, or several in a row.

Return a new string with the words in reverse order: the last word first and the first word last. Each word keeps its own characters in their original order. Put exactly one space between neighboring words and no space at the start or the end. There is always at least one word.

Example 1
Inputs = " read the logs "Output"logs the read"

The two spaces at the start and the one at the end are gone, and the three spaces between the and logs shrink to one. One space separates each pair of words.

Example 2
Inputs = "extract transform load"Output"load transform extract"
Example 3
Inputs = "batch"Output"batch"

One word in reverse order is the same word.

Constraints
  • 1 ≤ len(s) ≤ 2 × 106

  • Every character is an English letter, a digit or a space.

  • At least one character is not a space.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.