File: reverse-only-letters/solution.py

Date: 2026-06-06

Time: 18:53

Purpose

This file implements LeetCode problem 917 - Reverse Only Letters. It provides a Solution class with a method that reverses only the English alphabetic characters in a string while leaving all non-letter characters (digits, punctuation, spaces) in their original positions.

Note: the method is misnamed numrescueboats — this is a copy-paste artifact from a different problem. The docstring and implementation correctly solve "Reverse Only Letters."

Key Components

Solution.numrescueboats(self, s: str) -> str

Contract: Takes a string s, returns a new string where all isalpha() characters appear in reverse order but non-alpha characters remain at their original indices.

Example: "a-bC-dEf-ghIj""j-Ih-gfE-dCba"

Patterns

Two-pointer convergence: Classic technique where left starts at 0 and right at len-1. Both pointers move inward, skipping non-letter characters. When both point at letters, the values are swapped. This avoids needing to extract letters, reverse them, and re-insert — doing the work in a single pass over the array.

The string is converted to a list first since Python strings are immutable, then joined back at the end.

Dependencies

Imports: None — uses only Python builtins (str.isalpha, list, str.join).

Imported by: reverse-only-letters/test_solution.py (and hundreds of other test files that appear to share a common test harness importing all solutions).

Flow

1. Convert s to a mutable list of characters

2. Initialize two pointers at the string boundaries

3. Loop while left < right:

4. Join and return the result

The elif/else structure means exactly one pointer moves (or both move on swap) per iteration, guaranteeing O(n) time with O(n) space for the list copy.

Invariants

Error Handling

None. The method trusts that s is a valid string. Empty strings and single-character strings work correctly — the while left < right guard handles both cases by skipping the loop entirely.

Topics to Explore

Beliefs