Reverse Only Letters Problem & Solution

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.

See the reverse only letters problem on LeetCode.

C++ Solution

#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")

static const int _=[](){ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();

class Solution {
  string reverseOnlyLetters(string s) {
    int low = 0;
    int high = s.size() - 1;

    while (low < high) {
      char llow = tolower(s[low]);
      if (llow < 'a' || llow > 'z') {

      char lhigh = tolower(s[high]);
      if (lhigh < 'a' || lhigh > 'z') {

      swap(s[low], s[high]);

    return s;

Start Here

Many paths, there are. Follow yours, you must.