Reverse Words in a String II — LeetCode 186 Python Solution

MediumLeetCode PremiumTwo PointersString
Problem
#186
Reading time
3 min

The problem

Given a character array s, reverse the order of the words. A word is defined as a sequence of non-space characters.

Example

Input
s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output
["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Python solution

Python
class Solution:
    def reverseWords(self, s: List[str]) -> None:
        def reverse(i: int, j: int):
            while i < j:
                s[i], s[j] = s[j], s[i]
                i, j = i + 1, j - 1

        i, n = 0, len(s)
        for j, c in enumerate(s):
            if c == " ":
                reverse(i, j - 1)
                i = j + 1
            elif j == n - 1:
                reverse(i, j)
        reverse(0, n - 1)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the character array s
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 186. Reverse Words in a String II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 186. Reverse Words in a String II?
LeetCode 186. Reverse Words in a String II is rated Medium on LeetCode.
What is the time complexity of LeetCode 186. Reverse Words in a String II?
The Python solution on this page runs in O(n), where n is the length of the character array s.
What is the space complexity of LeetCode 186. Reverse Words in a String II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 186. Reverse Words in a String II cover?
LeetCode 186. Reverse Words in a String II is tagged Two Pointers and String on LeetCode.
Is LeetCode 186. Reverse Words in a String II a premium problem?
Yes. LeetCode 186. Reverse Words in a String II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview