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 INPUT String s = "ab-cd" a idx 0 b idx 1 - idx 2 c idx 3 d idx 4 Letter (to reverse) Non-letter (stays) L R Two Pointer Approach ALGORITHM STEPS 1 Initialize Pointers L=0 (start), R=4 (end) 2 Skip Non-Letters Move L/R if not a letter 3 Swap Letters Swap s[L] with s[R] 4 Move Pointers L++, R-- until L >= R Trace: [a,b,-,c,d] L=0,R=4 [d,b,-,c,a] swap a,d [d,b,-,c,a] L=1,R=3 [d,c,-,b,a] swap b,c [d,c,-,b,a] Done! FINAL RESULT Output: "dc-ba" d idx 0 c idx 1 - idx 2 b idx 3 a idx 4 Before vs After: a b - c d --> d c - b a OK - Verified! Complexity: Time: O(n) Space: O(n) for result Key Insight: Use two pointers (left and right) to swap only English letters while preserving non-letter characters in their original positions. Skip non-letters by moving the appropriate pointer until both point to letters, then swap and continue. TutorialsPoint - Reverse Only Letters | Optimal Two-Pointer Solution
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