Reverse Only Letters(#917)

Category: String, Two Pointer

๐Ÿงฉ Problem Statement

Given a string s, we need to reverse only the English letters โ€” both lowercase and uppercase โ€” while keeping all other characters like digits, dashes, and symbols in their original positions.

๐Ÿ“š Examples

Input: ab-cd

Output: dc-ba

Explanation: Only a, b, c, d are letters. The hyphen stays in place.

Input: a-bC-dEf-ghIj

Output: j-Ih-gfE-dCba

Explanation: The dashes remain fixed, and the letters are reversed.

Input: Test1ng-Leet=code-Q!

Output: Qedo1ct-eeLg=ntse-T!

Explanation: Even with numbers and symbols, only the letters are reversed.

๐Ÿง  Approach

### Two Pointer Technique

โ€ข Initialize two pointers, `left` at 0 and `right` at the end of the string.

โ€ข While `left < right`:

โ€ข If `s[left]` is not a letter, increment `left`.

โ€ข If `s[right]` is not a letter, decrement `right`.

โ€ข If both are letters, swap them and move both pointers.

โ€ข Use a helper function `isLetter()` to check for alphabetic characters.

โ€ข Finally, join the array back into a string.

๐Ÿ’ป Code

var reverseOnlyLetters = function(s) {
  const isLetter = (char) => {
    const code = char.charCodeAt(0);
    return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
  };

  let chars = s.split("");
  let left = 0, right = chars.length - 1;

  while (left < right) {
    if (!isLetter(chars[left])) {
      left++;
    } else if (!isLetter(chars[right])) {
      right--;
    } else {
      [chars[left], chars[right]] = [chars[right], chars[left]];
      left++;
      right--;
    }
  }

  return chars.join("");
};

๐Ÿ“ˆ Complexity

Time: O(n) โ€” Each character is visited at most once by either pointer.

Space: O(n) โ€” Because we split the string into a new array.

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources