Reverse Only the Vowels of a String

easy string two pointers

Problem

Reverse the order of the vowels in a string while leaving every consonant in place. Use two pointers that walk inward; whenever both land on a vowel, swap them. Treat both lower-case and upper-case a, e, i, o, u as vowels.

Inputs = "lighthouse"
Output"leghtiouse"
Vowels were i, o, u, e → reversed they become e, u, o, i in the same vowel slots.

def reverse_vowels(s):
    v = set("aeiouAEIOU")
    a = list(s)
    l, r = 0, len(a) - 1
    while l < r:
        while l < r and a[l] not in v: l += 1
        while l < r and a[r] not in v: r -= 1
        a[l], a[r] = a[r], a[l]; l += 1; r -= 1
    return "".join(a)
function reverseVowels(s) {
  const v = "aeiouAEIOU";
  const a = s.split("");
  let l = 0, r = a.length - 1;
  while (l < r) {
    while (l < r && !v.includes(a[l])) l++;
    while (l < r && !v.includes(a[r])) r--;
    [a[l], a[r]] = [a[r], a[l]]; l++; r--;
  }
  return a.join("");
}
class Solution {
    public String reverseVowels(String s) {
        String v = "aeiouAEIOU";
        char[] a = s.toCharArray();
        int l = 0, r = a.length - 1;
        while (l < r) {
            while (l < r && v.indexOf(a[l]) == -1) l++;
            while (l < r && v.indexOf(a[r]) == -1) r--;
            char tmp = a[l]; a[l] = a[r]; a[r] = tmp; l++; r--;
        }
        return new String(a);
    }
}
string reverseVowels(string s) {
    string v = "aeiouAEIOU";
    int l = 0, r = (int)s.size() - 1;
    while (l < r) {
        while (l < r && v.find(s[l]) == string::npos) l++;
        while (l < r && v.find(s[r]) == string::npos) r--;
        swap(s[l], s[r]); l++; r--;
    }
    return s;
}
Time: O(n) Space: O(n)