09 Sept 2026Go / Python / TypeScriptEasy

Reverse Only Letters

Reverse only the letters in a string while leaving non-letter characters fixed.

Move two pointers inward until both point at letters, swap them, and skip punctuation in place.

complexity

O(n) time and O(n) space for the mutable character array.

solution files

  • Go reverse-only-letters/solution.go
  • Python reverse-only-letters/solution.py
  • TypeScript reverse-only-letters/solution.ts

Solution files

Goreverse-only-letters/solution.go
package main

import "unicode"

func reverseOnlyLetters(s string) string {
	characters := []rune(s)
	left, right := 0, len(characters)-1
	for left < right {
		if !unicode.IsLetter(characters[left]) {
			left++
		} else if !unicode.IsLetter(characters[right]) {
			right--
		} else {
			characters[left], characters[right] = characters[right], characters[left]
			left++
			right--
		}
	}
	return string(characters)
}
Pythonreverse-only-letters/solution.py
class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        characters = list(s)
        left, right = class="syntax-number">0, len(characters) - class="syntax-number">1
        while left < right:
            if not characters[left].isalpha(): left += class="syntax-number">1
            elif not characters[right].isalpha(): right -= class="syntax-number">1
            else:
                characters[left], characters[right] = characters[right], characters[left]
                left, right = left + class="syntax-number">1, right - class="syntax-number">1
        return class="syntax-string">"".join(characters)
TypeScriptreverse-only-letters/solution.ts
function reverseOnlyLetters(s: string): string {
  const characters = [...s];
  const isLetter = (value: string): boolean => /[A-Za-z]/.test(value);
  let left = class="syntax-number">0;
  let right = characters.length - class="syntax-number">1;
  while (left < right) { if (!isLetter(characters[left])) left += class="syntax-number">1; else if (!isLetter(characters[right])) right -= class="syntax-number">1; else { [characters[left], characters[right]] = [characters[right], characters[left]]; left += class="syntax-number">1; right -= class="syntax-number">1; } }
  return characters.join(class="syntax-string">"");
}