Reverse Only Letters

Vivek Singh
1 min readOct 25, 2022

Given a string s, reverse the string according to the following rules:

  • All the characters that are not English letters remain in the same position.
  • All the English letters (lowercase or uppercase) should be reversed.

Return s after reversing it.

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"

Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Constraints:

  • 1 <= s.length <= 100
  • s consists of characters with ASCII values in the range [33, 122].
  • s does not contain '\"' or '\\'.

Solution:

Here we will follow two pointer approach. Left and right pointer.

Left pointer will keep increasing and right pointer will keep decreasing till they cross the path except one condition ( If character is not a letter).

Complexity: Big O(N)

public class Solution {
public string ReverseOnlyLetters(string s) {
char[] ch = s.ToCharArray();
// Two Pointer approach.
int left = 0;
int right = ch.Length-1;
//Check if string has only one character.
if(left == right)
return s;

while(left<= right)
{
if(Char.IsLetter(ch[left]) && Char.IsLetter(ch[right]))
{
char temp = ch[right];
ch[right]= ch[left];
ch[left] = temp;
left++;
right--;
}
if(!Char.IsLetter(ch[left]))
{
left++;

}
if(!Char.IsLetter(ch[right]))
{
right--;

}
}
return new string(ch);

}
}

--

--