I encountered the Reverse Vowel problem on Leetcode and decided to tackle it using the Two Pointers pattern. Here is the implementation:
var reverseVowels = function(s) {
let arrS = s.split('')
let vowels = ['a','e','i','o','u'];
let start = 0;
let end = arrS.length - 1;
while(start < end) {
if(!vowels.includes(arrS[start]) && !vowels.includes(arrS[end])) {
start++;
end--;
} else if(vowels.includes(arrS[start]) && !vowels.includes(arrS[end])) {
end--;
} else if(!vowels.includes(arrS[start]) && vowels.includes(arrS[end])) {
start++;
} else if(vowels.includes(arrS[start]) && vowels.includes(arrS[end])) {
let elementAtLo = arrS[start]
arrS[start] = arrS[end];
arrS[end] = elementAtLo;
start++;
end--;
}
}
return arrS.join('')
};
In the above code, I attempt to swap vowels found at both pointers. However, when I use the following code
arrS[start] = arrS[end];
arrS[end] = arrS[start];
the function fails to produce the correct output. But when I make use of this exchange:
let elementAtLo = arrS[start]
arrS[start] = arrS[end];
arrS[end] = elementAtLo;
everything works as intended. Can someone explain why one method works while the other does not?
I am struggling to comprehend the logic behind the success of my implementation.