Reverse Only Letters — LeetCode 917 Python Solution

EasyTwo PointersString
Problem
#917
Reading time
2 min

The problem

Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed.

Example

Input
s = "ab-cd"
Output
"dc-ba"

Python solution

Python
class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        cs = list(s)
        i, j = 0, len(cs) - 1
        while i < j:
            while i < j and not cs[i].isalpha():
                i += 1
            while i < j and not cs[j].isalpha():
                j -= 1
            if i < j:
                cs[i], cs[j] = cs[j], cs[i]
                i, j = i + 1, j - 1
        return "".join(cs)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 917. Reverse Only Letters 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 917. Reverse Only Letters?
LeetCode 917. Reverse Only Letters is rated Easy on LeetCode.
What is the time complexity of LeetCode 917. Reverse Only Letters?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 917. Reverse Only Letters?
The Python solution on this page uses O(n), where n is the length of the string auxiliary space.
What topics does LeetCode 917. Reverse Only Letters cover?
LeetCode 917. Reverse Only Letters 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