Practice › Strings
Reverse Only the Vowels
Easy · Strings · Asked at Google, Amazon, TCS, Infosys, Wipro
Reverse the order of the vowels (a e i o u, in lower or upper case) in the string, leaving every other character where it is. Print the result.
Input
A single line with the string (letters only).
Output
The string with its vowels reversed.
Constraints
- 1 ≤ length ≤ 10^5
Two pointers from both ends: move each one inward until it sits on a vowel, swap the two vowels, and continue.
Example 1
Input
hello
Output
holle
Example 2
Input
IceCreAm
Output
AceCreIm
Hints
- Only the vowels move; think of them as a separate sequence that gets reversed.
- Two pointers from both ends can swap them in place.
Approach
Keep i at the start and j at the end. Move i right until it is on a vowel and j left until it is on a vowel; swap them and step both inward. Stop when they meet. Every other character never moves.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
bool isVowel(char c) {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int main() {
string s;
cin >> s;
int i = 0, j = (int) s.size() - 1;
while (i < j) {
if (!isVowel(s[i])) i++;
else if (!isVowel(s[j])) j--;
else swap(s[i++], s[j--]);
}
cout << s << "\n";
return 0;
}Python solution
s = list(input().strip())
vowels = set("aeiouAEIOU")
i, j = 0, len(s) - 1
while i < j:
if s[i] not in vowels:
i += 1
elif s[j] not in vowels:
j -= 1
else:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
print("".join(s))Java solution
import java.io.*;
public class Main {
static boolean isVowel(char c) {
return "aeiouAEIOU".indexOf(c) >= 0;
}
public static void main(String[] args) throws IOException {
char[] s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim().toCharArray();
int i = 0, j = s.length - 1;
while (i < j) {
if (!isVowel(s[i])) i++;
else if (!isVowel(s[j])) j--;
else {
char t = s[i];
s[i++] = s[j];
s[j--] = t;
}
}
System.out.println(new String(s));
}
}Solve Reverse Only the Vowels online · All practice problems