Magicsheet logo

Reverse Only Letters

Easy
39.6%
Updated 6/1/2025

Reverse Only Letters

What is this problem about?

The Reverse Only Letters interview question gives you a string containing letters and non-letter characters (digits, punctuation, spaces). You must reverse only the letters in the string while keeping all non-letter characters in their exact original positions. The result is a string of the same length where letters appear in reversed order and non-letters stay put.

Why is this asked in interviews?

This problem is asked at Microsoft, Zoho, Nvidia, Snowflake, Amazon, and Google because it is a clean application of the two-pointer technique with a character-type filtering condition. It tests whether candidates can extend the classic "reverse a string" approach to handle skip conditions — a pattern relevant to text processors, format-preserving transformations, and data masking systems.

Algorithmic pattern used

The pattern is the two-pointer technique with character-type skipping. Convert the string to a list for mutability. Place left at index 0 and right at index len(s)-1. While left < right: advance left rightward until it points to a letter. Advance right leftward until it points to a letter. Swap the characters at left and right. Then advance both pointers inward. After the loop, join and return the list.

Example explanation

Input: "a-bC-dEf-ghIj"

Convert to list. left=0, right=13.

  • left=0 ('a' — letter), right=13 ('j' — letter) → swap → 'j' and 'a'.
  • left=1, but '-' → skip. left=2 ('b' — letter). right=12, 'I' → swap 'b' and 'I'.
  • left=4 ('C'). right=10 ('h') → swap.
  • left=6 ('d'). right=9 ('g') → swap.
  • left=8 ('E'). right=7 ('f') → left ≥ right → stop.

Result: "j-Ih-gEf-dCba".

(Exact result depends on the example, but the pattern holds.)

Common mistakes candidates make

  • Forgetting to skip non-letter characters on both sides — skipping only on one side produces incorrect results.
  • Checking isalpha() incorrectly for accented characters or Unicode letters.
  • Not converting the string to a mutable structure (list) before swapping — strings are immutable in Python.
  • Advancing only one pointer after swapping instead of both.

Interview preparation tip

For the Reverse Only Letters coding problem, the two-pointer and string interview pattern is the right approach. The key extension to the basic reverse is the "skip non-letters" logic on both pointers. Microsoft and Snowflake interviewers may generalize: "What if you only reversed digits?" — the same pattern applies with isdigit() instead of isalpha(). Practice implementing both the letter-only and digit-only variants to show generalization.

Similar Questions