Reverse Words in a String III — LeetCode 557 Python Solution

EasyTwo PointersString
Problem
#557
Reading time
2 min

The problem

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example

Input
s = "Let's take LeetCode contest"
Output
"s'teL ekat edoCteeL tsetnoc"

Python solution

Python
class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(t[::-1] for t in s.split())

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 557. Reverse Words in a String III 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 557. Reverse Words in a String III?
LeetCode 557. Reverse Words in a String III is rated Easy on LeetCode.
What is the time complexity of LeetCode 557. Reverse Words in a String III?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 557. Reverse Words in a String III?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 557. Reverse Words in a String III cover?
LeetCode 557. Reverse Words in a String III 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