File: reverse-vowels-of-a-string/solution.py

Date: 2026-06-06

Time: 18:54

Purpose

This file implements LeetCode 345 — Reverse Vowels of a String. It owns a single responsibility: given a string, return a new string where only the vowel characters have their positions reversed, while all non-vowel characters stay in place.

It lives under reverse-vowels-of-a-string/solution.py following the repo's convention of one problem per directory with solution.py, test_solution.py, plan.md, and review.md.

Key Components

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

The only method. Contract:

vowels constant (local)

set("aeiouAEIOU") — a set of 10 characters covering both cases. Using a set gives O(1) membership testing instead of O(10) linear scan on a string.

Patterns

Two-pointer inward sweep. left starts at 0, right at the last index. Both march inward:

This is the canonical in-place two-pointer pattern for "reverse a subset of elements." It's the same structure used in reverse-only-letters/solution.py (swap letters, skip non-letters).

Mutable list copy. Python strings are immutable, so the string is converted to list(s) for O(1) swaps, then joined back at the end. This avoids O(n^2) string concatenation.

Dependencies

Imports: none — the solution is self-contained with no stdlib or third-party imports.

Imported by: reverse-vowels-of-a-string/test_solution.py directly. The "Imported By" list in the prompt is misleading — those are all test files across the repo that import their *own* solution.py, not this one. The actual consumer is only the local test file.

Flow

1. Build a set of vowel characters (both cases).

2. Convert s to a mutable chars list.

3. Initialize left = 0, right = len(chars) - 1.

4. Loop while left < right:

5. Join and return.

Each character is visited at most once by each pointer, so the total work is O(n) time, O(n) space (for the list copy).

Invariants

Error Handling

None. The method assumes valid input per LeetCode constraints. An empty string or single-character string works correctly — the while loop simply never executes, and "".join(chars) returns the original string.

Topics to Explore

Beliefs