Ctrl K

Reverse the Word Order in Place

Medium
You get a list of characters chars holding a phrase whose words are separated by exactly one space, with no spaces at the start or the end. A word is an unbroken run of non-space characters. Put the words in reverse order; each word itself still reads the same. Return the list with the words reversed. Try not to build an extra list: rearrange the characters inside chars itself with O(1) memory.
Example 1
chars=['g', 'o', ' ', 'f', 'a', 's', 't'] → ['f', 'a', 's', 't', ' ', 'g', 'o']

The words go and fast swap: the list becomes ['f', 'a', 's', 't', ' ', 'g', 'o'].

Example 2
chars=['A', ' ', 'b', ' ', '7'] → ['7', ' ', 'b', ' ', 'A']

The result is ['7', ' ', 'b', ' ', 'A'].

Example 3
chars=['o', 'k'] → ['o', 'k']

There is only one word, so the list stays the same.

Constraints
  • 1 ≤ len(chars) ≤ 10⁵
  • Each chars[i] is an English letter, a digit or a space
  • There is at least one word
  • No leading or trailing spaces; words are separated by exactly one space
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumWords in Reverse Order MediumExactly One Edit Apart MediumWhich Release Is Newer MediumPacking Runs in Place Medium
loading Python…
Input
chars=['g', 'o', ' ', 'f', 'a', 's', 't']
Expected
['f', 'a', 's', 't', ' ', 'g', 'o']

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