Problem summary: Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"IceCreAm"
Example 2
"leetcode"
Related Problems
Reverse String (reverse-string)
Remove Vowels from a String (remove-vowels-from-a-string)
Faulty Keyboard (faulty-keyboard)
Sort Vowels in a String (sort-vowels-in-a-string)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #345: Reverse Vowels of a String
class Solution {
public String reverseVowels(String s) {
boolean[] vowels = new boolean[128];
for (char c : "aeiouAEIOU".toCharArray()) {
vowels[c] = true;
}
char[] cs = s.toCharArray();
int i = 0, j = cs.length - 1;
while (i < j) {
while (i < j && !vowels[cs[i]]) {
++i;
}
while (i < j && !vowels[cs[j]]) {
--j;
}
if (i < j) {
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
++i;
--j;
}
}
return String.valueOf(cs);
}
}
// Accepted solution for LeetCode #345: Reverse Vowels of a String
func reverseVowels(s string) string {
vowels := [128]bool{}
for _, c := range "aeiouAEIOU" {
vowels[c] = true
}
cs := []byte(s)
i, j := 0, len(cs)-1
for i < j {
for i < j && !vowels[cs[i]] {
i++
}
for i < j && !vowels[cs[j]] {
j--
}
if i < j {
cs[i], cs[j] = cs[j], cs[i]
i, j = i+1, j-1
}
}
return string(cs)
}
# Accepted solution for LeetCode #345: Reverse Vowels of a String
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = "aeiouAEIOU"
i, j = 0, len(s) - 1
cs = list(s)
while i < j:
while i < j and cs[i] not in vowels:
i += 1
while i < j and cs[j] not in vowels:
j -= 1
if i < j:
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j - 1
return "".join(cs)
// Accepted solution for LeetCode #345: Reverse Vowels of a String
impl Solution {
pub fn reverse_vowels(s: String) -> String {
let vowel = String::from("aeiouAEIOU");
let mut data: Vec<char> = s.chars().collect();
let (mut i, mut j) = (0, s.len() - 1);
while i < j {
while i < j && !vowel.contains(data[i]) {
i += 1;
}
while i < j && !vowel.contains(data[j]) {
j -= 1;
}
if i < j {
data.swap(i, j);
i += 1;
j -= 1;
}
}
data.iter().collect()
}
}
// Accepted solution for LeetCode #345: Reverse Vowels of a String
function reverseVowels(s: string): string {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
const cs = s.split('');
for (let i = 0, j = cs.length - 1; i < j; ++i, --j) {
while (i < j && !vowels.has(cs[i].toLowerCase())) {
++i;
}
while (i < j && !vowels.has(cs[j].toLowerCase())) {
--j;
}
[cs[i], cs[j]] = [cs[j], cs[i]];
}
return cs.join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.