Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"ab-cd"
Example 2
"a-bC-dEf-ghIj"
Example 3
"Test1ng-Leet=code-Q!"
Related Problems
Faulty Keyboard (faulty-keyboard)
Reverse Letters Then Special Characters in a String (reverse-letters-then-special-characters-in-a-string)
Step 02
Core Insight
What unlocks the optimal approach
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #917: Reverse Only Letters
class Solution {
public String reverseOnlyLetters(String s) {
char[] cs = s.toCharArray();
int i = 0, j = cs.length - 1;
while (i < j) {
while (i < j && !Character.isLetter(cs[i])) {
++i;
}
while (i < j && !Character.isLetter(cs[j])) {
--j;
}
if (i < j) {
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
++i;
--j;
}
}
return new String(cs);
}
}
// Accepted solution for LeetCode #917: Reverse Only Letters
func reverseOnlyLetters(s string) string {
cs := []rune(s)
i, j := 0, len(s)-1
for i < j {
for i < j && !unicode.IsLetter(cs[i]) {
i++
}
for i < j && !unicode.IsLetter(cs[j]) {
j--
}
if i < j {
cs[i], cs[j] = cs[j], cs[i]
i++
j--
}
}
return string(cs)
}
# Accepted solution for LeetCode #917: Reverse Only Letters
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
cs = list(s)
i, j = 0, len(cs) - 1
while i < j:
while i < j and not cs[i].isalpha():
i += 1
while i < j and not cs[j].isalpha():
j -= 1
if i < j:
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j - 1
return "".join(cs)
// Accepted solution for LeetCode #917: Reverse Only Letters
impl Solution {
pub fn reverse_only_letters(s: String) -> String {
let mut cs: Vec<char> = s.chars().collect();
let n = cs.len();
let mut l = 0;
let mut r = n - 1;
while l < r {
if !cs[l].is_ascii_alphabetic() {
l += 1;
} else if !cs[r].is_ascii_alphabetic() {
r -= 1;
} else {
cs.swap(l, r);
l += 1;
r -= 1;
}
}
cs.iter().collect()
}
}
// Accepted solution for LeetCode #917: Reverse Only Letters
function reverseOnlyLetters(s: string): string {
const cs = [...s];
let [i, j] = [0, cs.length - 1];
while (i < j) {
while (!/[a-zA-Z]/.test(cs[i]) && i < j) {
i++;
}
while (!/[a-zA-Z]/.test(cs[j]) && i < j) {
j--;
}
[cs[i], cs[j]] = [cs[j], cs[i]];
i++;
j--;
}
return cs.join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.