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
Input: a-bC-dEf-ghIj
Output: j-Ih-gfE-dCba
Input: Test1ng-Leet=code-Q!
Output: Qedo1ct-eeLg=ntse-T!
๐ง 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.