#2785

Sort Vowels in a String

Medium
StringSortingSortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

This approach utilizes a single pass to collect and sort the vowels while maintaining the positions of consonants. This is more efficient than the brute force method as it reduces unnecessary iterations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Traverse the string and collect all vowels into a list.
  2. 2Step 2: Sort the list of vowels.
  3. 3Step 3: Create a new list to build the result string, replacing vowels from the sorted list while keeping consonants in their original positions.
solution.py9 lines
1def sortVowels(s):
2    vowels = sorted([c for c in s if c in 'aeiouAEIOU'])
3    result = list(s)
4    vowel_index = 0
5    for i in range(len(s)):
6        if s[i] in 'aeiouAEIOU':
7            result[i] = vowels[vowel_index]
8            vowel_index += 1
9    return ''.join(result)

Complexity note: The time complexity is O(n log n) due to sorting the vowels, while the space complexity is O(n) for storing the vowels and the result.

  • 1Vowels can be sorted independently of consonants, allowing for efficient rearrangement.
  • 2Maintaining the original positions of consonants is crucial for the problem's requirements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.