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
Reverse Only Letters: Keep Non-Letters in PlaceInput String:ab-cdLetterLetterKeepLetterLetterReverse Letters: a,b,c,d → d,c,b,aOutput String:dc-baResult: "dc-ba"✓ Letters are reversed✓ Non-letters stay in place✓ Original structure preserved
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
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen