Reverse Only Letters | LeetCode 917 | Python | Solution

Click here to see the problem details.

Problem Overview

The problem description is pretty precise. It says that we have to return the reverse version of the given string. But we can only reverse letters. Characters that are not a letter stay in the same place. Only letters will change their position. Let’s see an example.

input = 'h1ell2o'
output = 'o1lle2h'

See the previous example. There every character changes the position except the two numbers. Cause numbers != letters. I hope you got the idea.

How can we solve this in code? Let’s get into the coding part.

Coding Part

To solve this problem, we use a stack. We all know about stack data structure. It follows the “First In First Out” (FIFO) rule.

If we store five characters in a stack and then pop all the characters from the stack one by one, we will get the reverse version of the five characters.

We will do the same things to solve this problem. First, we will run a loop through the given string. Using the loop, we will store all the letters in a stack. To check a character is a letter or not, we will use Python’s built-in function isalpha().

Now we will create a variable to store the final result. Then have to run another loop on the given string. This time we will check the current element. If the current one is a letter, we do not add it to the variable. Instead of adding it, we will add the character from the stack. Otherwise, we will add the current character into the variable. After the loop, we will get the final result and will return it.

Let’s see the code for a clear understanding.

class Solution:
    def reverseOnlyLetters(self, S: str) -> str:
        stack = []
        for el in S:
            if el.isalpha():
        result = ''
        for el in S:
            if el.isalpha():
                result += stack.pop()
                result += el
        return result

That’s all about the problem solution. I hope it will help you.

Scroll to Top