Reverse Vowels of a String

Problem

Given a string s, return a new string where only the vowels are reversed in order, while all other characters remain in their original positions.

  • 1 ≤ s.length ≤ 3 * 10⁵
  • s consists of printable ASCII characters.

Example

Input: s = "hello"
Output: "holle"

The vowels in "hello" are 'e' and 'o'. Reversing their order results in 'o' followed by 'e'. The algorithm uses two pointers starting at the beginning and end of the string, moving inward to find vowels to swap. Initially, left points to 'h' (not a vowel), so it moves right. Right points to 'o' (vowel). When both pointers point to vowels ('e' and 'o'), they are swapped. This process continues until the pointers meet or cross, resulting in the reversed vowel string.

Approach

Straightforward Solution

A naive approach collects all vowels in a list, reverses it, and then reconstructs the string by replacing vowels in order. This requires extra space proportional to the number of vowels and two passes over the string.

Core Observation

The problem requires reversing only vowels in a string, which suggests a two-pointer approach scanning from both ends to efficiently identify vowels to swap without extra space for vowel positions.

Path to Optimal

The key insight is to use two pointers starting at the beginning and end of the string, moving inward. Each pointer skips non-vowels until it finds a vowel. When both pointers point to vowels, swap them and move both pointers inward. This approach reverses vowels in-place with a single pass and O(1) extra space.

Optimal Approach

Convert the string to a list for mutability. Use two pointers, left and right, initialized at the start and end of the list. Move left forward until a vowel is found, move right backward until a vowel is found. Swap the vowels at left and right, then move both pointers inward. Continue until left >= right. Finally, join the list into a string and return it.

Time

O(n)

Each character is visited at most once by either the left or right pointer, resulting in a single linear pass through the string.

Space

O(n)

The input string is converted to a list of characters to allow in-place swaps, requiring O(n) auxiliary space proportional to the input size. No additional data structures proportional to input size are used.

Pattern Spotlight

Two Pointers (Greedy Contraction)

When reversing or rearranging elements under constraints, use two pointers from opposite ends to identify and swap target elements efficiently, discarding non-target elements by moving pointers inward until the condition is met.

Solution

1class Solution:
2 def reverseVowels(self, s: str) -> str:
3 vowels = set("aeiouAEIOU")
4 chars = list(s)
5
6 left = 0
7 right = len(chars) - 1
8
9 while left < right:
10 while left < right and chars[left] not in vowels:
11 left += 1
12
13 while left < right and chars[right] not in vowels:
14 right -= 1
15
16 chars[left], chars[right] = chars[right], chars[left]
17 left += 1
18 right -= 1
19
20 return "".join(chars)

Step-by-Step Solution

1

Initialize Vowel Set and Convert String to Mutable List

3vowels = set("aeiouAEIOU")
4chars = list(s)

Objective

To prepare for efficient vowel detection and enable in-place character swaps.

Key Insight

Using a set for vowels allows O(1) membership checks, which is critical for performance when scanning large strings. Converting the immutable string to a list enables swapping characters directly without creating new strings repeatedly, which would be costly.

Interview Quick-Check

Core Logic

A set of vowels provides constant-time membership checks, which is essential for efficient filtering during pointer traversal.

Common Pitfalls & Bugs

Forgetting to convert the string to a list would make swapping impossible or inefficient, as strings are immutable in Python.

2

Use Two Pointers to Locate and Swap Vowels While Moving Inward

6left = 0
7right = len(chars) - 1
9while left < right:
10 while left < right and chars[left] not in vowels:
11 left += 1
13 while left < right and chars[right] not in vowels:
14 right -= 1
16 chars[left], chars[right] = chars[right], chars[left]
17 left += 1
18 right -= 1

Objective

To identify vowels from both ends and swap them to reverse their order in the string.

Key Insight

The two-pointer technique efficiently narrows down the search space by skipping non-vowels from both ends. Swapping vowels when both pointers point to vowels ensures the reversal of vowel order without disturbing other characters. Incrementing and decrementing pointers after swaps prevents infinite loops and ensures progress toward termination.

Interview Quick-Check

Core Logic

The algorithm advances each pointer until it finds a vowel, then swaps the vowels at the pointers and moves both pointers inward, ensuring all vowels are reversed in a single pass.

State & Boundaries

The loop continues while left < right, ensuring pointers do not cross and all vowel pairs are processed exactly once.

Common Pitfalls & Bugs

Failing to check pointer bounds in the inner loops can cause index errors or infinite loops.

3

Reconstruct and Return the Resulting String

20return "".join(chars)

Objective

To convert the modified list of characters back into a string for the final output.

Key Insight

Joining the list into a string is necessary because the problem requires a string output. This step finalizes the in-place modifications made by the two-pointer swaps.

Interview Quick-Check

Core Logic

Joining the list of characters into a string returns the final result with vowels reversed and other characters unchanged.

Line Analysis

This solution has 1 Critical line interviewers watch for.

Line 16 Critical
chars[left], chars[right] = chars[right], chars[left]

Swap the vowels at the left and right pointers.

Swapping vowels reverses their order in the string while preserving the positions of non-vowel characters, which is the core operation of the algorithm.

Line 3 Core
vowels = set("aeiouAEIOU")

Initialize a set containing all vowels in lowercase and uppercase.

Using a set enables O(1) average-time membership checks, which is critical for efficiently identifying vowels during pointer traversal.

Line 4 Core
chars = list(s)

Convert the input string into a list of characters for in-place modification.

Strings are immutable in Python, so converting to a list allows swapping characters directly without creating new strings repeatedly, improving performance.

Line 10 Core
while left < right and chars[left] not in vowels:

Advance the left pointer forward while it points to a non-vowel and is less than right.

Skipping non-vowels on the left side efficiently narrows the search to the next vowel to swap, avoiding unnecessary operations.

Line 13 Core
while left < right and chars[right] not in vowels:

Advance the right pointer backward while it points to a non-vowel and is greater than left.

Skipping non-vowels on the right side efficiently narrows the search to the next vowel to swap, maintaining the two-pointer strategy.

Line 20 Core
return "".join(chars)

Join the list of characters into a string and return it.

Converting the list back to a string produces the final output in the required format, completing the transformation.

Line 9 Standard
while left < right:

Start a loop that continues while the left pointer is less than the right pointer.

This condition ensures that vowel pairs are processed only once and prevents pointers from crossing, which would indicate completion.

Line 17 Standard
left += 1

Increment the left pointer to move inward after swapping.

Advancing the left pointer after a swap prevents re-processing the same vowel and ensures progress toward loop termination.

Line 18 Standard
right -= 1

Decrement the right pointer to move inward after swapping.

Moving the right pointer inward after a swap prevents re-processing the same vowel and ensures progress toward loop termination.

Line 11 Standard
left += 1

Increment the left pointer by one.

Moving the pointer forward is necessary to progress the search for the next vowel and avoid infinite loops.

Line 14 Standard
right -= 1

Decrement the right pointer by one.

Moving the pointer backward is necessary to progress the search for the next vowel and avoid infinite loops.

Line 6 Standard
left = 0

Initialize the left pointer at the start of the character list.

The left pointer will scan forward to find vowels from the beginning of the string.

Line 7 Standard
right = len(chars) - 1

Initialize the right pointer at the end of the character list.

The right pointer will scan backward to find vowels from the end of the string.

Test Your Understanding

Why does moving the pointers inward only when vowels are found guarantee that all vowels are reversed correctly?

Because the two-pointer approach ensures that each vowel from the start is paired with a vowel from the end, swapping them in order. Skipping non-vowels preserves their positions, and moving inward guarantees all vowel pairs are processed exactly once, resulting in a correct reversal.

Related Problems

Two Pointers pattern

Don't just read it. Drill it.

Reconstruct Reverse Vowels of a String from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Reverse Vowels of a String drill

or drill a free problem