Problem summary: You are given a string s consisting of lowercase English letters and special characters. Your task is to perform these in order: Reverse the lowercase letters and place them back into the positions originally occupied by letters. Reverse the special characters and place them back into the positions originally occupied by special characters. Return the resulting string after performing the reversals.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
")ebc#da@f("
Example 2
"z"
Example 3
"!@#$%^&*()"
Related Problems
Reverse Only Letters (reverse-only-letters)
Step 02
Core Insight
What unlocks the optimal approach
Use two pointers from ends, skipping non-letters.
Use two pointers from ends, skipping letters.
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 #3823: Reverse Letters Then Special Characters in a String
class Solution {
public String reverseByType(String s) {
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
char[] t = s.toCharArray();
for (char c : t) {
if (Character.isLetter(c)) {
a.append(c);
} else {
b.append(c);
}
}
int j = a.length(), k = b.length();
for (int i = 0; i < t.length; ++i) {
if (Character.isLetter(t[i])) {
t[i] = a.charAt(--j);
} else {
t[i] = b.charAt(--k);
}
}
return new String(t);
}
}
// Accepted solution for LeetCode #3823: Reverse Letters Then Special Characters in a String
func reverseByType(s string) string {
a := make([]byte, 0)
b := make([]byte, 0)
t := []byte(s)
for _, c := range t {
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') {
a = append(a, c)
} else {
b = append(b, c)
}
}
j, k := len(a), len(b)
for i := 0; i < len(t); i++ {
if (t[i] >= 'A' && t[i] <= 'Z') || (t[i] >= 'a' && t[i] <= 'z') {
j--
t[i] = a[j]
} else {
k--
t[i] = b[k]
}
}
return string(t)
}
# Accepted solution for LeetCode #3823: Reverse Letters Then Special Characters in a String
class Solution:
def reverseByType(self, s: str) -> str:
a = []
b = []
for c in s:
if c.isalpha():
a.append(c)
else:
b.append(c)
return ''.join(a.pop() if c.isalpha() else b.pop() for c in s)
// Accepted solution for LeetCode #3823: Reverse Letters Then Special Characters in a String
fn reverse_by_type(s: String) -> String {
let len = s.len();
let cs: Vec<_> = s.chars().collect();
let mut ret: Vec<char> = cs.clone();
let mut left = 0;
let mut right = len - 1;
while left < right {
while left < len && !cs[left].is_ascii_alphabetic() {
left += 1;
}
while right > 0 && !cs[right].is_ascii_alphabetic() {
right -= 1;
}
if left >= right {
break;
}
ret[left] = cs[right];
ret[right] = cs[left];
left += 1;
right -= 1;
}
left = 0;
right = len - 1;
while left < right {
while left < len && cs[left].is_ascii_alphabetic() {
left += 1;
}
while right > 0 && cs[right].is_ascii_alphabetic() {
right -= 1;
}
if left >= right {
break;
}
ret[left] = cs[right];
ret[right] = cs[left];
left += 1;
right -= 1;
}
ret.into_iter().collect()
}
fn main() {
let ret = reverse_by_type(")ebc#da@f(".to_string());
println!("ret={ret}");
}
#[test]
fn test() {
assert_eq!(reverse_by_type("(q".to_string()), "(q");
assert_eq!(reverse_by_type(")ebc#da@f(".to_string()), "(fad@cb#e)");
assert_eq!(reverse_by_type("z".to_string()), "z");
assert_eq!(reverse_by_type("!@#$%^&*()".to_string()), ")(*&^%$#@!");
}
// Accepted solution for LeetCode #3823: Reverse Letters Then Special Characters in a String
function reverseByType(s: string): string {
const a: string[] = [];
const b: string[] = [];
const t = s.split('');
for (const c of t) {
if (/[a-zA-Z]/.test(c)) {
a.push(c);
} else {
b.push(c);
}
}
let j = a.length,
k = b.length;
for (let i = 0; i < t.length; i++) {
if (/[a-zA-Z]/.test(t[i])) {
t[i] = a[--j];
} else {
t[i] = b[--k];
}
}
return t.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.