Reverse Words in a String — LeetCode 151 Python Solution

MediumTwo PointersString
Problem
#151
Reading time
2 min

The problem

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

Example

Input
s = "the sky is blue"
Output
"blue is sky the"

Python solution

Python
class Solution:
    def reverseWords(self, s: str) -> str:
        words = []
        i, n = 0, len(s)
        while i < n:
            while i < n and s[i] == " ":
                i += 1
            if i < n:
                j = i
                while j < n and s[j] != " ":
                    j += 1
                words.append(s[i:j])
                i = j
        return " ".join(words[::-1])

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 151. Reverse Words in a String 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

On study lists

This problem is on LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 151. Reverse Words in a String?
LeetCode 151. Reverse Words in a String is rated Medium on LeetCode.
What is the time complexity of LeetCode 151. Reverse Words in a String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 151. Reverse Words in a String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 151. Reverse Words in a String cover?
LeetCode 151. Reverse Words in a String is tagged Two Pointers and String on LeetCode.

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