Reverse Only Letters (LeetCode 917): Solution and Explanation

Easy
Two Pointers
String

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

  1. Copy the string into a mutable character array.
  2. Set i = 0 and j = n - 1.
  3. While i < j: if chars[i] is not a letter, move i right.
  4. Else if chars[j] is not a letter, move j left.
  5. Otherwise swap chars[i] and chars[j], then move both pointers inward.
  6. Return the array joined back into a string.

Step-by-step example

s = "ab-cd"
  1. i = 0 ('a') and j = 4 ('d') are both letters. Swap: "db-ca". Now i = 1, j = 3.
  2. i = 1 ('b') and j = 3 ('c') are both letters. Swap: "dc-ba". Now i = 2, j = 2.
  3. i is no longer less than j, so the loop stops. The dash never moved.
  4. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each step moves at least one pointer inward, so there are at most n steps.

Space

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.