Skip to content

Instantly share code, notes, and snippets.

@mtzfox
Last active July 12, 2023 05:56
Show Gist options
  • Save mtzfox/129f874f72b50d070b27450590f8192b to your computer and use it in GitHub Desktop.
Save mtzfox/129f874f72b50d070b27450590f8192b to your computer and use it in GitHub Desktop.
Reverse vowels of a string
var reverseVowels = function (s) {
let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
let strArr = [...s];
let foundVowels = [];
for (let i = s.length - 1; i >= 0; i--) {
if (vowels.includes(s[i])) {
foundVowels.push(s[i]);
}
}
for (let j = 0; j < strArr.length; j++) {
if (vowels.includes(strArr[j])) {
strArr[j] = foundVowels[0];
foundVowels.splice(0, 1);
}
}
return strArr.join('');
};
// Small refactor - removed console(log) and swapped conditions in the while loops - much faster
var reverseVowels = function(s) {
let vowels = [ 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ];
s = [...s ];
for (let i = 0, j = s.length - 1; i < j;) {
while (i < s.length && !vowels.includes(s[i])) {
i++;
}
while (j >= 0 && !vowels.includes(s[j])) {
j--;
}
if (i < j) {
// shorthand for swapping and then incrementing
[s[i++], s[j--]] = [ s[j], s[i]];
}
}
return s.join('');
};
// Third refactor
var reverseVowels = function (s) {
let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
s = [...s];
let i = 0,
j = s.length - 1;
while (i < j) {
if (vowels.includes(s[i]) && vowels.includes(s[j])) {
[s[i++], s[j--]] = [s[j], s[i]];
}
if (!vowels.includes(s[i])) {
i++;
}
if (!vowels.includes(s[j])) {
j--;
}
}
return s.join('');
};
@mtzfox
Copy link
Author

mtzfox commented Jul 12, 2023

Original

Idea: find all of the vowels in a word, reverse them, and then replace the reversed order back in the original word.

I finished but it was slow: Runtime 172 ms, Beats 8.58%

Though process:
Likely slow because of the two separate loops. My method was to have the first loop run backward to check if current letter was included in an array of upper and lowercase vowels and then push them to a new array, though I could have just gone forward and then reversed the array.

The second loop then inserts the found vowels back into an array from the given string by checking for the vowel and then assigning the first value of the found array and then removing it.

Thinking now that there might be a way to do both actions in a single loop, though I'm not sure how to replace without first reversing the entire loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment