We need to process the string and identify groups of consecutive vowels. For each such group:
If its length is exactly 2, we append both vowels and then add '$'
.
If the group length is 1 or >2, we just append the vowels as they are.
For consonants, we simply append them to the result.
Instead of inserting characters directly into the original string (which is inefficient due to shifting elements), we build a new string (result
) by scanning the input once.
Identify vowels:
Create a helper function isVowel(char c)
to quickly check if a character is a vowel (a, e, i, o, u
).
Traverse the string:
Use a pointer i
to iterate through the string.
When you find a vowel:
Start another pointer j
from i
to find the length of the consecutive vowel group.
Append each vowel from i
to j-1
into the result.
Add '$' when necessary:
If the length of this vowel group (len = j - i
) is exactly 2, append a '$'
.
Handle consonants:
If the current character is not a vowel, append it directly to the result.
Update i
:
Move i
to j
to continue scanning.
Output:
Print the final result
string.
#include<bits/stdc++.h>
using namespace std;
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int main() {
int n;
string s;
cin >> n >> s;
string result = "";
int i = 0;
while (i < n) {
if (isVowel(s[i])) {
int j = i;
while (j < n && isVowel(s[j])) {
result += s[j];
j++;
}
int len = j - i;
if (len == 2) result += '$'; // Insert $ only for exactly 2 vowels
i = j;
} else {
result += s[i];
i++;
}
}
cout << result << endl;
return 0;
}
Time Complexity: O(n)
Each character in the input string is processed exactly once.
Space Complexity: O(n)
We store the output string in result
.