Reverse Only Letters

(#917), Easy

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 inward.
  • Use a helper function `isLetter()` to check for alphabetic characters.
  • Finally, join the character array back into a string and return.
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