Skip to content

Instantly share code, notes, and snippets.

@clayton-perszyk
Created February 9, 2018 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clayton-perszyk/b6ac88645bbd01cd57d81fb47cabff8c to your computer and use it in GitHub Desktop.
Save clayton-perszyk/b6ac88645bbd01cd57d81fb47cabff8c to your computer and use it in GitHub Desktop.
/*$
reverseVowels(word) -
Given an array of characters,
reverse the vowels but keep the consonants in place.
Space complexity: O(1)
Time complexity: O(N)
Example: ["w","h","i","t","e","b","o","a","r","d"] ->
["w","h","a","t","o","b","e","i","r","d"]
*/
const letters = ["w","h","i","t","e","b","o","a","r","d"];
function reverseVowels(word) {
let vowels = /[aeiou]/
let start = 0;
let end = word.length - 1;
let temp;
while (start !== end) {
if (!word[start].match(vowels) && !word[end].match(vowels)) {
start += 1;
end -= 1;
}
if (word[start].match(vowels) && !word[end].match(vowels)) {
start += 1;
}
if (!word[start].match(vowels) && word[end].match(vowels)) {
start += 1;
}
if (word[start].match(vowels) && word[end].match(vowels)) {
temp = word[start];
word[start] = word[end];
word[end] = temp;
start += 1;
end -= 1;
}
}
return word;
}
console.log(reverseVowels(letters));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment