Similar Problems

Similar Problems not available

Reverse Only Letters - Leetcode Solution

Companies:

LeetCode:  Reverse Only Letters Leetcode Solution

Difficulty: Easy

Topics: string two-pointers  

Problem Description: Given a string s, reverse the string according to the following rules:

  • All the characters that are not a letter stays in the same position.
  • All the letters stay at their respective positions.

Solution Steps:

  1. Initialize two pointers, left and right, representing the start and end of the string.
  2. Start looping over the string using these pointers. Inside the loop, perform the following steps: a. Check if the left pointer is pointing to a letter. If it is a letter, go to the next step. If not, move the left pointer to the right. b. Check if the right pointer is pointing to a letter. If it is a letter, go to the next step. If not, move the right pointer to the left. c. If both the left and right pointers are pointing to letters, swap their values. d. Move the left pointer to the right and the right pointer to the left.
  3. Return the reversed string.

Code:

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        # Convert the string into a list
        lst = list(s)
        # Initialize the left and right pointers
        left, right = 0, len(s)-1
        while left < right:
            # Check if left is pointing to a letter
            if not lst[left].isalpha():
                left += 1
                continue
            # Check if right is pointing to a letter
            if not lst[right].isalpha():
                right -= 1
                continue
            # Swap values of left and right
            lst[left], lst[right] = lst[right], lst[left]
            # Move the pointers
            left += 1
            right -= 1
        # Convert the list back into a string and return
        return ''.join(lst)

Time Complexity: O(n) - where n is the length of the string s Space Complexity: O(n) - since we are using a list to store the string characters.

Reverse Only Letters Solution Code

1