Skip to main content

Reverse Vowels of a String

LeetCode 345 | Difficulty: Easy​

Easy

Problem Description​

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.

Example 1:

Input: s = "IceCreAm"

Output: "AceCreIm"

Explanation:

The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

Example 2:

Input: s = "leetcode"

Output: "leotcede"

Constraints:

- `1 <= s.length <= 3 * 10^5`

- `s` consist of **printable ASCII** characters.

Topics: Two Pointers, String


Approach​

Direct Approach​

This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.

When to use

Basic problems that test fundamental programming skills.


Solutions​

Solution 1: C# (Best: 136 ms)​

MetricValue
Runtime136 ms
MemoryN/A
Date2018-04-05
Solution
public class Solution {
public string ReverseVowels(string s) {
char[] sArray = s.ToCharArray();
int len = s.Length;
if(String.IsNullOrEmpty(s) || len==1) return s;
int i=0, j=len-1;
while(i<j)
{
while(!IsVowel(sArray[i]) && i<j)
{
i++;
}
while(!IsVowel(sArray[j]) && i<j)
{
j--;
}
if(i<j)
{
char temp = sArray[i];
sArray[i] = sArray[j];
sArray[j] = temp;
}
i++;
j--;
}
return new string(sArray);
}

public bool IsVowel(char c)
{
char[] vowels = {'A','E','I','O','U','a','e','i','o','u'};
return vowels.Contains(c);
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.