Reverse Only Letters — LeetCode 917 Python Solution
- Problem
- #917
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.