🔗 Problem Link
LeetCode 917 – Reverse Only Letters
👉 https://leetcode.com/problems/reverse-only-letters/
Introduction
This is a very clean two-pointer problem.
The challenge is not just reversing a string —
it’s reversing only the letters while keeping all non-letter characters in their original positions.
This problem strengthens:
- Two pointer technique
- Character validation logic
- In-place string manipulation
Let’s break it down.
📌 Problem Understanding
You are given a string s.
Rules:
- All non-English letters must remain at the same index.
- Only English letters (uppercase or lowercase) should be reversed.
Return the modified string.
Example 1
Only letters are reversed.
Hyphen stays at same position.
Example 2
Example 3
Notice:
- Numbers,
-,=,!stay fixed. - Only letters move.
🧠 Intuition
The first thought might be:
- Extract all letters
- Reverse them
- Put them back
But that would require extra space.
Instead, we can solve this efficiently using Two Pointers.
🚀 Two Pointer Approach
We use:
i→ starting from leftj→ starting from right
Steps:
- Convert string into char array.
- Move
iforward until it points to a letter. - Move
jbackward until it points to a letter. - Swap letters.
- Continue until
i < j.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Convert to Character Array
Strings are immutable in Java.
So we convert to char array to modify it.
2️⃣ Initialize Two Pointers
We start from both ends.
3️⃣ Check If Characters Are Letters
You manually check ASCII ranges for uppercase and lowercase letters.
Same logic for r.
4️⃣ Swap When Both Are Letters
Only swap letters.
5️⃣ Move Pointers When One Is Not Letter
- If left is letter but right is not → move
j - If right is letter but left is not → move
i - If both are not letters → move both
This ensures:
Non-letter characters remain in their positions.
🎯 Why This Works
We never move non-letter characters.
We only swap valid letters.
Since we use two pointers:
- Time complexity stays linear.
- No extra array needed for letters.
⏱ Complexity Analysis
Time Complexity: O(n)
Each character is visited at most once.
Space Complexity: O(n)
Because we convert string to char array.
(If considering output string creation, still O(n))
🔥 Cleaner Optimization
Instead of manually checking ASCII ranges, Java provides:
Cleaner version:
Much cleaner and readable.
🏁 Final Thoughts
This problem teaches:
- Two pointer pattern
- In-place string reversal
- Character validation logic
- Clean pointer movement strategy
It’s a simple but powerful pattern that appears often in interviews.
If you master this, you can easily solve:
- Reverse Vowels of a String
- Valid Palindrome
- Reverse String II
- Palindrome with One Removal




