algoadvance

Leetcode 917. Reverse Only Letters

Problem Statement

You are given a string s which consists of lowercase and uppercase letters. Reverse only the letters and leave all other characters at their original positions.

Example 1:

Example 2:

Example 3:

Constraints:

Clarifying Questions

  1. Does the input string include symbols, digits, and spaces?
    • Answer: The problem statement implies that s consists of various characters, not limited to letters.
  2. Should the case sensitivity of letters be maintained?
    • Answer: Yes, maintain the case sensitivity (lowercase should remain lowercase and uppercase should remain uppercase).
  3. Are there any special performance requirements?
    • Answer: None specified, but an efficient solution is always desirable.

Strategy

  1. Two-pointer Approach: Use two pointers, one starting from the beginning and the other from the end. Move both pointers towards the center of the string.
  2. Swap Letters: When both pointers point to a letter, swap the letters.
  3. Skip Non-Letters: If a pointer points to a non-letter, move that pointer inward without making a swap.
  4. Stop Condition: Continue the process until the two pointers cross each other.

Code

public class ReverseOnlyLetters {
    public String reverseOnlyLetters(String s) {
        char[] arr = s.toCharArray();
        int left = 0;
        int right = arr.length - 1;
        
        while (left < right) {
            if (!Character.isLetter(arr[left])) {
                left++;
            } else if (!Character.isLetter(arr[right])) {
                right--;
            } else {
                char temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }
        
        return new String(arr);
    }

    public static void main(String[] args) {
        ReverseOnlyLetters solution = new ReverseOnlyLetters();
        System.out.println(solution.reverseOnlyLetters("ab-cd")); // "dc-ba"
        System.out.println(solution.reverseOnlyLetters("a-bC-dEf-ghIj")); // "j-Ih-gfE-dCba"
        System.out.println(solution.reverseOnlyLetters("Test1ng-Leet=code-Q!")); // "Qedo1ct-eeLg=ntse-T!"
    }
}

Time Complexity

This approach is efficient and fulfills the problem’s requirements effectively.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI