345. Reverse Vowels of a String LeetCode Solution
In this guide, you will get 345. Reverse Vowels of a String LeetCode Solution with the best time and space complexity. The solution to Reverse Vowels of a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Reverse Vowels of a String solution in C++
- Reverse Vowels of a String solution in Java
- Reverse Vowels of a String solution in Python
- Additional Resources

Problem Statement of Reverse Vowels of a String
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 * 105
s consist of printable ASCII characters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
345. Reverse Vowels of a String LeetCode Solution in C++
class Solution {
public:
string reverseVowels(string s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
while (l < r && !isVowel(s[l]))
++l;
while (l < r && !isVowel(s[r]))
--r;
swap(s[l++], s[r--]);
}
return s;
}
private:
bool isVowel(char c) {
static constexpr string_view kVowels = "aeiouAEIOU";
return kVowels.find(c) != string_view::npos;
}
};
/* code provided by PROGIEZ */
345. Reverse Vowels of a String LeetCode Solution in Java
class Solution {
public String reverseVowels(String s) {
StringBuilder sb = new StringBuilder(s);
int l = 0;
int r = s.length() - 1;
while (l < r) {
while (l < r && !isVowel(sb.charAt(l)))
++l;
while (l < r && !isVowel(sb.charAt(r)))
--r;
sb.setCharAt(l, s.charAt(r));
sb.setCharAt(r, s.charAt(l));
++l;
--r;
}
return sb.toString();
}
private boolean isVowel(char c) {
return "aeiouAEIOU".indexOf(c) != -1;
}
}
// code provided by PROGIEZ
345. Reverse Vowels of a String LeetCode Solution in Python
class Solution:
def reverseVowels(self, s: str) -> str:
chars = list(s)
kVowels = 'aeiouAEIOU'
l = 0
r = len(s) - 1
while l < r:
while l < r and chars[l] not in kVowels:
l += 1
while l < r and chars[r] not in kVowels:
r -= 1
chars[l], chars[r] = chars[r], chars[l]
l += 1
r -= 1
return ''.join(chars)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.