Sort Vowels in a String

medium string sorting

Problem

You are given a string s of uppercase and lowercase English letters. Build a new string t of the same length where every consonant keeps exactly the position it had in s, while the vowels (a, e, i, o, u in either case) are rearranged among the vowel positions so that their ASCII values are in nondecreasing order.

Remember that every uppercase vowel has a smaller ASCII value than every lowercase vowel, so for example 'E' and 'O' must come before 'e'.

Inputs = "lEetcOde"
Output"lEOtcede"
The vowels E, e, O, e sort by ASCII to E, O, e, e and refill slots 1, 2, 5, 7; consonants l, t, c, d never move.

def sort_vowels(s):
    vowels = set("aeiouAEIOU")
    picked = [c for c in s if c in vowels]
    picked.sort()
    out = []
    k = 0
    for c in s:
        if c in vowels:
            out.append(picked[k])
            k += 1
        else:
            out.append(c)
    return "".join(out)
function sortVowels(s) {
  const vowels = new Set("aeiouAEIOU");
  const picked = [...s].filter(c => vowels.has(c));
  picked.sort();
  let k = 0;
  let out = "";
  for (const c of s) {
    if (vowels.has(c)) {
      out += picked[k++];
    } else {
      out += c;
    }
  }
  return out;
}
String sortVowels(String s) {
    String vs = "aeiouAEIOU";
    List<Character> picked = new ArrayList<>();
    for (char c : s.toCharArray())
        if (vs.indexOf(c) >= 0) picked.add(c);
    Collections.sort(picked);
    StringBuilder out = new StringBuilder();
    int k = 0;
    for (char c : s.toCharArray()) {
        if (vs.indexOf(c) >= 0) out.append(picked.get(k++));
        else out.append(c);
    }
    return out.toString();
}
string sortVowels(string s) {
    string vs = "aeiouAEIOU";
    string picked;
    for (char c : s)
        if (vs.find(c) != string::npos) picked += c;
    sort(picked.begin(), picked.end());
    int k = 0;
    for (char &c : s)
        if (vs.find(c) != string::npos) c = picked[k++];
    return s;
}
Time: O(n log n) Space: O(n)