KatInterview

953. Reverse Only Letters

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reverse a given string, but with a specific rule: only the English letters (both lowercase and uppercase) should be reversed, while all other characters must remain in their original positions. For example, in "a-bC-d", the letters are a, b, C, d. Their reversed order is d, C, b, a. Placing them back into the letter slots of the original string gives "d-Cb-a".

Solution

Reverse Only Letters in Python

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        # Convert the string to a list of characters because strings are immutable in Python.
        chars = list(s)
        left, right = 0, len(chars) - 1

        while left < right:
            # Move the left pointer forward until it points to an English letter.
            # The condition `left < right` is crucial to prevent pointers from crossing.
            while left < right and not chars[left].isalpha():
                left += 1
            
            # Move the right pointer backward until it points to an English letter.
            while left < right and not chars[right].isalpha():
                right -= 1

            # If left is still less than right, it means we have found two letters to swap.
            if left < right:
                # Swap the letters at the left and right pointers.
                chars[left], chars[right] = chars[right], chars[left]
                
                # Move both pointers towards the center.
                left += 1
                right -= 1
        
        # Join the list of characters back into a string.
        return "".join(chars)

Reverse Only Letters in Java

class Solution {
    public String reverseOnlyLetters(String s) {
        // Convert the string to a character array because strings are immutable in Java.
        char[] chars = s.toCharArray();
        int left = 0;
        int right = chars.length - 1;

        while (left < right) {
            // Move the left pointer forward until it points to an English letter.
            // The condition `left < right` is crucial to prevent pointers from crossing.
            while (left < right && !Character.isLetter(chars[left])) {
                left++;
            }

            // Move the right pointer backward until it points to an English letter.
            while (left < right && !Character.isLetter(chars[right])) {
                right--;
            }

            // If left is still less than right, it means we have found two letters to swap.
            if (left < right) {
                // Swap the letters at the left and right pointers.
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;

                // Move both pointers towards the center.
                left++;
                right--;
            }
        }

        // Convert the character array back to a string.
        return new String(chars);
    }
}

Reverse Only Letters in C++

class Solution {
public:
    string reverseOnlyLetters(string s) {
        int left = 0;
        int right = s.length() - 1;

        while (left < right) {
            // Move the left pointer forward until it points to an English letter.
            // The condition `left < right` is crucial to prevent pointers from crossing.
            while (left < right && !isalpha(s[left])) {
                left++;
            }

            // Move the right pointer backward until it points to an English letter.
            while (left < right && !isalpha(s[right])) {
                right--;
            }

            // If left is still less than right, it means we have found two letters to swap.
            if (left < right) {
                // Swap the letters at the left and right pointers.
                swap(s[left], s[right]);

                // Move both pointers towards the center.
                left++;
                right--;
            }
        }

        return s;
    }
};

Reverse Only Letters in TypeScript

function reverseOnlyLetters(s: string): string {
    // Convert the string to an array of characters because strings are immutable in TypeScript.
    const chars = s.split('');
    let left = 0;
    let right = chars.length - 1;

    const isLetter = (char: string): boolean => {
        return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');
    };

    while (left < right) {
        // Move the left pointer forward until it points to an English letter.
        // The condition `left < right` is crucial to prevent pointers from crossing.
        while (left < right && !isLetter(chars[left])) {
            left++;
        }

        // Move the right pointer backward until it points to an English letter.
        while (left < right && !isLetter(chars[right])) {
            right--;
        }

        // If left is still less than right, it means we have found two letters to swap.
        if (left < right) {
            // Swap the letters at the left and right pointers using array destructuring.
            [chars[left], chars[right]] = [chars[right], chars[left]];

            // Move both pointers towards the center.
            left++;
            right--;
        }
    }

    // Join the array of characters back into a string.
    return chars.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.