Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created September 11, 2025 22:40
Show Gist options
  • Select an option

  • Save Ifihan/b0e1cb8e165f02c34f2868a734251218 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/b0e1cb8e165f02c34f2868a734251218 to your computer and use it in GitHub Desktop.
Sort Vowels in a String

Question

Approach

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.

Implementation

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)

Complexities

  • 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
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment