Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.
Examples:
Input: "geeksforgeeks"
Output: "geeksforgeeks"
Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"
Output: "hollowerld"
Explanation: The vowels 'e', 'o', 'o' are reversed, resulting in "hollowerld".Input: "programming"
Output: "prigrammong"
Explanation: The vowels 'o', 'a', 'i' are reversed, resulting in "prigrammong".
Table of Content
[Brute-Force Approach] Store and Replace Vowels - O(n) Time and O(n) Space
The idea is to extract all vowels from the given string s and store them in vowelStr while maintaining their order. Then, we iterate through s again, replacing each vowel with the last stored vowel from vowelStr, effectively reversing their positions. This approach works because only vowels are modified, while consonants remain in place.
Below is the implementation of the above approach:
// C++ program to reverse order of vowels
// in a string using BruteForce method
#include <bits/stdc++.h>
using namespace std;
// Function to check if a character is a vowel
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
string reverseVowels(string &s) {
string vowelStr;
// Store all vowels in vowelStr
for (int i = 0; i < s.length(); i++) {
if (isVowel(s[i])) {
vowelStr += s[i];
}
}
// Reverse read vowels and replace in string
int idx = vowelStr.size() - 1;
for (int i = 0; i < s.length(); i++) {
if (isVowel(s[i])) {
s[i] = vowelStr[idx--];
}
}
return s;
}
int main() {
string s = "geeksforgeeks";
cout << reverseVowels(s) << endl;
return 0;
}
// Java program to reverse order of vowels
// in a string using BruteForce method
import java.util.*;
class GfG {
// Function to check if a character is a vowel
static boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
static String reverseVowels(String s) {
StringBuilder vowelStr = new StringBuilder();
// Store all vowels in vowelStr
for (int i = 0; i < s.length(); i++) {
if (isVowel(s.charAt(i))) {
vowelStr.append(s.charAt(i));
}
}
// Reverse read vowels and replace in string
StringBuilder result = new StringBuilder(s);
int idx = vowelStr.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (isVowel(s.charAt(i))) {
result.setCharAt(i, vowelStr.charAt(idx--));
}
}
return result.toString();
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(reverseVowels(s));
}
}
# Python program to reverse order of vowels
# in a string using BruteForce method
# Function to check if a character is a vowel
def isVowel(c):
return c == 'a' or c == 'e' or c == 'i' \
or c == 'o' or c == 'u'
def reverseVowels(s):
vowelStr = ""
# Store all vowels in vowelStr
for i in range(len(s)):
if isVowel(s[i]):
vowelStr += s[i]
# Reverse read vowels and replace in string
result = list(s)
idx = len(vowelStr) - 1
for i in range(len(s)):
if isVowel(s[i]):
result[i] = vowelStr[idx]
idx -= 1
return "".join(result)
if __name__ == "__main__":
s = "geeksforgeeks"
print(reverseVowels(s))
// C# program to reverse order of vowels
// in a string using BruteForce method
using System;
class GfG {
// Function to check if a character is a vowel
static bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
static string reverseVowels(string s) {
string vowelStr = "";
// Store all vowels in vowelStr
for (int i = 0; i < s.Length; i++) {
if (isVowel(s[i])) {
vowelStr += s[i];
}
}
// Reverse read vowels and replace in string
char[] result = s.ToCharArray();
int idx = vowelStr.Length - 1;
for (int i = 0; i < s.Length; i++) {
if (isVowel(s[i])) {
result[i] = vowelStr[idx--];
}
}
return new string(result);
}
static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(reverseVowels(s));
}
}
// JavaScript program to reverse order of vowels
// in a string using BruteForce method
// Function to check if a character is a vowel
function isVowel(c) {
return c === 'a' || c === 'e' || c === 'i'
|| c === 'o' || c === 'u';
}
function reverseVowels(s) {
let vowelStr = "";
// Store all vowels in vowelStr
for (let i = 0; i < s.length; i++) {
if (isVowel(s[i])) {
vowelStr += s[i];
}
}
// Reverse read vowels and replace in string
let result = s.split("");
let idx = vowelStr.length - 1;
for (let i = 0; i < s.length; i++) {
if (isVowel(s[i])) {
result[i] = vowelStr[idx--];
}
}
return result.join("");
}
let s = "geeksforgeeks";
console.log(reverseVowels(s));
Output
geeksforgeeks
Time Complexity: O(n), as first pass collects vowels, second pass replaces them in reverse order, and each pass costs O(n).
Space Complexity: O(n), as extra space is used to store vowels separately.
[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space
The idea is to use the Two Pointers technique to efficiently reverse only the vowels in the string while keeping other characters in place. We maintain left and right pointers, moving them inward until they find a vowel. Once both pointers point to vowels, we swap them.
Steps to implement the above idea:
- Initialize left at the start and right at the end of the string to track vowel positions.
- Use a while loop to iterate until left is smaller than right, ensuring all vowels are processed.
- Move left forward until a vowel is found, skipping non-vowel characters efficiently.
- Move right backward until a vowel is found, ensuring only vowels are considered for swapping.
- If both left and right point to vowels, swap them to reverse their order.
- Increment left and decrement right to continue checking remaining characters in the string.
- Return the modified string after all vowels have been reversed while maintaining original positions.
Below is the implementation of the above approach:
// C++ program to reverse order of vowels
// in a string using Two Pointers method
#include <bits/stdc++.h>
using namespace std;
// Function to check if a character is a vowel
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
string reverseVowels(string &s) {
int left = 0, right = s.length() - 1;
// Two-pointer approach to swap vowels
while (left < right) {
// Move left pointer until a vowel is found
while (left < right && !isVowel(s[left])) {
left++;
}
// Move right pointer until a vowel is found
while (left < right && !isVowel(s[right])) {
right--;
}
// Swap the vowels
if (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
return s;
}
int main() {
string s = "geeksforgeeks";
cout << reverseVowels(s) << endl;
return 0;
}
// Java program to reverse order of vowels
// in a string using Two Pointers method
import java.util.*;
class GfG {
// Function to check if a character is a vowel
static boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
static String reverseVowels(String s) {
char[] str = s.toCharArray();
int left = 0, right = str.length - 1;
// Two-pointer approach to swap vowels
while (left < right) {
// Move left pointer until a vowel is found
while (left < right && !isVowel(str[left])) {
left++;
}
// Move right pointer until a vowel is found
while (left < right && !isVowel(str[right])) {
right--;
}
// Swap the vowels
if (left < right) {
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
return new String(str);
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(reverseVowels(s));
}
}
# Python program to reverse order of vowels
# in a string using Two Pointers method
# Function to check if a character is a vowel
def isVowel(c):
return c in "aeiou"
def reverseVowels(s):
s = list(s)
left, right = 0, len(s) - 1
# Two-pointer approach to swap vowels
while left < right:
# Move left pointer until a vowel is found
while left < right and not isVowel(s[left]):
left += 1
# Move right pointer until a vowel is found
while left < right and not isVowel(s[right]):
right -= 1
# Swap the vowels
if left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return "".join(s)
if __name__ == "__main__":
s = "geeksforgeeks"
print(reverseVowels(s))
// C# program to reverse order of vowels
// in a string using Two Pointers method
using System;
class GfG {
// Function to check if a character is a vowel
static bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u';
}
static string reverseVowels(string s) {
char[] str = s.ToCharArray();
int left = 0, right = str.Length - 1;
// Two-pointer approach to swap vowels
while (left < right) {
// Move left pointer until a vowel is found
while (left < right && !isVowel(str[left])) {
left++;
}
// Move right pointer until a vowel is found
while (left < right && !isVowel(str[right])) {
right--;
}
// Swap the vowels
if (left < right) {
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
return new string(str);
}
public static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(reverseVowels(s));
}
}
// JavaScript program to reverse order of vowels
// in a string using Two Pointers method
// Function to check if a character is a vowel
function isVowel(c) {
return "aeiou".includes(c);
}
function reverseVowels(s) {
let str = s.split("");
let left = 0, right = str.length - 1;
// Two-pointer approach to swap vowels
while (left < right) {
// Move left pointer until a vowel is found
while (left < right && !isVowel(str[left])) {
left++;
}
// Move right pointer until a vowel is found
while (left < right && !isVowel(str[right])) {
right--;
}
// Swap the vowels
if (left < right) {
[str[left], str[right]] = [str[right], str[left]];
left++;
right--;
}
}
return str.join("");
}
let s = "geeksforgeeks";
console.log(reverseVowels(s));
Output
geeksforgeeks
Time Complexity: O(n), as each character is processed at most once.
Space Complexity: O(1), since only a few extra variables are used.