Ctrl K

Words in Reverse Order

Medium
You get a string text of English letters, digits and spaces. A word is any unbroken run of non-space characters. Return a string with the same words in reverse order, separated by exactly one space. The input may have spaces at the start, at the end, and several in a row between words; the answer must have no extra spaces. If strings are mutable in your language, try to use only O(1) extra memory.
Example 1
text="keep calm and code" → 'code and calm keep'
Example 2
text="   north  wind " → 'wind north'

The spaces at the edges go away and the double space becomes a single one: wind north.

Example 3
text="Room 42" → '42 Room'

Digits are part of a word too: 42 Room.

Constraints
  • 1 ≤ len(text) ≤ 10⁴
  • text consists of English letters, digits and spaces
  • text contains at least one word
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumExactly One Edit Apart MediumWhich Release Is Newer MediumReverse the Word Order in Place MediumPacking Runs in Place Medium
loading Python…
Input
text="keep calm and code"
Expected
'code and calm keep'

Run checks the first 3 tests in your browser. Submit checks all 4 tests on the server, hidden ones included.