Reverse Only Letters (LeetCode 917): Solution and Explanation
Reverse the English letters of a string while every non-letter character keeps its original index.
Intuition
If you wrote down only the letters and reversed them, the first letter would trade places with the last letter, the second with the second-to-last, and so on.
Non-letters never move, so they act like pins. The letter slots between them are filled in mirrored order.
Two pointers walking inward from both ends find each mirrored pair directly: skip a pointer past pins, and when both sit on letters, swap.
Approach: Two pointers skipping non-letters
- Copy the string into a mutable character array.
- Set
i = 0andj = n - 1. - While
i < j: ifchars[i]is not a letter, moveiright. - Else if
chars[j]is not a letter, movejleft. - Otherwise swap
chars[i]andchars[j], then move both pointers inward. - Return the array joined back into a string.
Step-by-step example
s = "ab-cd"
- i = 0 ('a') and j = 4 ('d') are both letters. Swap: "db-ca". Now i = 1, j = 3.
- i = 1 ('b') and j = 3 ('c') are both letters. Swap: "dc-ba". Now i = 2, j = 2.
- i is no longer less than j, so the loop stops. The dash never moved.
- Return "dc-ba".
Code: Python, Java, C++
1class Solution:
2 def reverseOnlyLetters(self, s: str) -> str:
3 chars = list(s)
4 i, j = 0, len(chars) - 1
5 while i < j:
6 if not chars[i].isalpha():
7 i += 1
8 elif not chars[j].isalpha():
9 j -= 1
10 else:
11 chars[i], chars[j] = chars[j], chars[i]
12 i += 1
13 j -= 1
14 return ''.join(chars)1class Solution {
2 public String reverseOnlyLetters(String s) {
3 char[] chars = s.toCharArray();
4 int i = 0, j = chars.length - 1;
5 while (i < j) {
6 if (!Character.isLetter(chars[i])) {
7 i++;
8 } else if (!Character.isLetter(chars[j])) {
9 j--;
10 } else {
11 char tmp = chars[i];
12 chars[i++] = chars[j];
13 chars[j--] = tmp;
14 }
15 }
16 return new String(chars);
17 }
18}1class Solution {
2public:
3 string reverseOnlyLetters(string s) {
4 int i = 0, j = (int)s.size() - 1;
5 while (i < j) {
6 if (!isalpha(s[i])) {
7 i++;
8 } else if (!isalpha(s[j])) {
9 j--;
10 } else {
11 swap(s[i++], s[j--]);
12 }
13 }
14 return s;
15 }
16};Time and space complexity
O(n)
Each step moves at least one pointer inward, so there are at most n steps.
O(n)
Strings are immutable in most languages, so we use a character array of length n. In C++ the string is modified in place with O(1) extra space.
Other approaches
Stack of letters (time O(n), space O(n))
Push all letters onto a stack. Then rebuild the string: copy non-letters as they are and pop the stack for every letter slot.
Reverse letters separately (time O(n), space O(n))
Extract the letters into a list, reverse it, and write them back into the letter positions in order.
Common mistakes
- Reversing the whole string and then trying to fix the symbols. Their positions are lost after the reversal.
- Moving both pointers when only one of them sits on a non-letter. Only the pointer on the non-letter should move.
- Using a locale-aware letter check that accepts characters outside A to Z. Here only ASCII letters count.
Frequently asked questions
Why does the loop use i < j and not i <= j?
When i equals j there is a single character left in the middle. Swapping it with itself changes nothing.
Are digits letters here?
No. Only a to z and A to Z are letters, so digits stay at their positions like any other symbol.
What if the string has no letters at all?
Every step moves a pointer past a non-letter, no swaps happen, and the string comes back unchanged.