917. Reverse Only Letters LeetCode Solution

In this guide, you will get 917. Reverse Only Letters LeetCode Solution with the best time and space complexity. The solution to Reverse Only Letters problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Reverse Only Letters solution in C++
  4. Reverse Only Letters solution in Java
  5. Reverse Only Letters solution in Python
  6. Additional Resources
917. Reverse Only Letters LeetCode Solution image

Problem Statement of Reverse Only Letters

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 '\\'.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

917. Reverse Only Letters LeetCode Solution in C++

class Solution {
 public:
  string reverseOnlyLetters(string s) {
    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      while (i < j && !isalpha(s[i]))
        ++i;
      while (i < j && !isalpha(s[j]))
        --j;
      swap(s[i], s[j]);
    }
    return s;
  }
};
/* code provided by PROGIEZ */

917. Reverse Only Letters LeetCode Solution in Java

class Solution {
  public String reverseOnlyLetters(String s) {
    StringBuilder sb = new StringBuilder(s);

    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      while (i < j && !Character.isLetter(s.charAt(i)))
        ++i;
      while (i < j && !Character.isLetter(s.charAt(j)))
        --j;
      sb.setCharAt(i, s.charAt(j));
      sb.setCharAt(j, s.charAt(i));
    }

    return sb.toString();
  }
}
// code provided by PROGIEZ

917. Reverse Only Letters LeetCode Solution in Python

class Solution:
  def reverseOnlyLetters(self, s: str) -> str:
    ans = list(s)
    i = 0
    j = len(s) - 1

    while i < j:
      while i < j and not s[i].isalpha():
        i += 1
      while i < j and not s[j].isalpha():
        j -= 1
      ans[i], ans[j] = ans[j], ans[i]
      i += 1
      j -= 1

    return ''.join(ans)
# code by PROGIEZ

Additional Resources

See also  977. Squares of a Sorted Array LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.