MediumNo. 2785

Sort Vowels in a String — LeetCode 2785 Python Solution

Pattern
Sorting
Topics
String, Sorting
Reading time
2 min

The problem

Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].

Example

Input
s = "lEetcOde"
Output
"lEOtcede"
Explanation
'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.

Python solution

PythonSolution
class Solution:
    def sortVowels(self, s: str) -> str:
        vs = [c for c in s if c.lower() in "aeiou"]
        vs.sort()
        cs = list(s)
        j = 0
        for i, c in enumerate(cs):
            if c.lower() in "aeiou":
                cs[i] = vs[j]
                j += 1
        return "".join(cs)

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2785. Sort Vowels in a String is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0539Minimum Time DifferenceMedium
0899Orderly QueueHard
0937Reorder Data in Log FilesMedium
1451Rearrange Words in a SentenceMedium
1859Sorting the SentenceEasy
0056Merge IntervalsMedium

Frequently asked questions

How hard is LeetCode 2785. Sort Vowels in a String?

LeetCode 2785. Sort Vowels in a String is rated Medium on LeetCode.

What is the time complexity of LeetCode 2785. Sort Vowels in a String?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 2785. Sort Vowels in a String?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2785. Sort Vowels in a String cover?

LeetCode 2785. Sort Vowels in a String is tagged String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.