Sort Vowels in a String — LeetCode 2785 Python Solution
- Problem
- #2785
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
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
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 \times \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.