I scan the string once, collecting the indices and characters of all vowels (treating vowels as a,e,i,o,u in both cases). I then sort just the vowel characters by their ASCII values (so uppercase come before lowercase), and write them back into the original string positions while leaving all consonants untouched.
class Solution:
def sortVowels(self, s: str) -> str:
V = set("aeiouAEIOU")
chars = list(s)
pos = []
vals = []
for i, ch in enumerate(chars):
if ch in V:
pos.append(i)
vals.append(ch)
vals.sort()
for i, ch in zip(pos, vals):
chars[i] = ch
return "".join(chars)- Time: O(n+vlogv), where 𝑛 is the string length and 𝑣 is the number of vowels (since only vowels are sorted)
- Space: O(v) to store vowel positions and values