Reverse Only Letters - Problem
Imagine you're a proofreader working with a document where all the English letters need to be reversed while keeping all other characters (numbers, symbols, spaces) in their exact positions!
Given a string s, your task is to reverse only the English letters according to these rules:
- All characters that are not English letters (a-z, A-Z) must remain in the same position
- All English letters (both lowercase and uppercase) should be reversed among themselves
Goal: Return the modified string after reversing only the letters.
Example: "ab-cd" becomes "dc-ba" - notice how the dash stays in position 2, but the letters a,b,c,d become d,c,b,a.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "ab-cd"
โบ
Output:
"dc-ba"
๐ก Note:
The letters are 'a', 'b', 'c', 'd'. When reversed, they become 'd', 'c', 'b', 'a'. The non-letter character '-' stays in position 2. So we get 'd' + 'c' + '-' + 'b' + 'a' = "dc-ba".
example_2.py โ Mixed Case with Numbers
$
Input:
s = "a-bC-dEf-ghIj"
โบ
Output:
"j-Ih-gfE-dCba"
๐ก Note:
Extract letters: a,b,C,d,E,f,g,h,I,j. Reversed: j,I,h,g,f,E,d,C,b,a. Place back while preserving positions of '-': "j-Ih-gfE-dCba".
example_3.py โ Edge Case - No Letters
$
Input:
s = "Test1ng-Leet=code-Q!"
โบ
Output:
"Qedo1ct-eeLg=ntse-T!"
๐ก Note:
Letters are: T,e,s,t,n,g,L,e,e,t,c,o,d,e,Q. Reversed: Q,e,d,o,c,t,e,e,L,g,n,t,s,e,T. Numbers and symbols stay in their positions.
Constraints
- 1 โค s.length โค 100
- s consists of printable ASCII characters
- Letters include both uppercase and lowercase English letters (a-z, A-Z)
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Gallery
Walk through and identify which display cases contain letters vs other artifacts
2
Two Curator Strategy
Position one curator at the entrance, another at the exit - they work toward the middle
3
Find and Swap
Each curator moves inward until finding a letter display, then they swap those artifacts
4
Continue Until Meeting
Repeat the process until both curators meet in the middle - all letters are now reversed!
Key Takeaway
๐ฏ Key Insight: The two-pointer approach elegantly handles this problem by treating letters and non-letters differently - we only swap letters while completely ignoring the positions of other characters. This results in optimal O(n) time complexity with a single pass through the string.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code