Reverse Only Letters - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "ab-cd"
›
Output:
"dc-ba"
💡 Note:
Letters are a,b,c,d. Reversed: d,c,b,a. Place back: d at pos 0, c at pos 1, skip -, b at pos 3, a at pos 4
Example 2 — Mixed Characters
$
Input:
s = "a-bC-dEf-ghIj"
›
Output:
"j-Ih-gfE-dCba"
💡 Note:
Letters: a,b,C,d,E,f,g,h,I,j. Reversed: j,I,h,g,f,E,d,C,b,a. Non-letters stay in same positions
Example 3 — No Letters
$
Input:
s = "Test1ng-Leet=code-Q!"
›
Output:
"Qedo1ct-eeLg=ntse-T!"
💡 Note:
Only letters are reversed: T,e,s,t,n,g,L,e,e,t,c,o,d,e,Q become Q,e,d,o,c,t,e,e,L,g,n,t,s,e,T
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of printable ASCII characters.
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with letters and non-letters mixed: "ab-cd"
2
Process
Reverse only the letters: a,b,c,d → d,c,b,a
3
Output
Non-letters stay in place: "dc-ba"
Key Takeaway
🎯 Key Insight: Use two pointers to swap only letters while skipping non-letters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code