Sort Vowels in a String - 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].
  • The vowels must be sorted in nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].

Return the resulting string.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

Input & Output

Example 1 — Basic Vowel Sorting
$ Input: s = "lEetcOde"
Output: "lEOtcede"
💡 Note: Consonants 'l', 't', 'c', 'd' stay in place. Vowels 'E', 'e', 'O', 'e' are sorted by ASCII: 'E'(69), 'O'(79), 'e'(101), 'e'(101) → 'E', 'O', 'e', 'e'
Example 2 — Mixed Case Vowels
$ Input: s = "lYmpH"
Output: "lYmpH"
💡 Note: No vowels present in the string, so the string remains unchanged. All characters 'l', 'Y', 'm', 'p', 'H' are consonants.
Example 3 — All Vowels
$ Input: s = "UeAiO"
Output: "AOUei"
💡 Note: All characters are vowels. Sort by ASCII: 'A'(65), 'O'(79), 'U'(85), 'e'(101), 'i'(105) → 'A', 'O', 'U', 'e', 'i'

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of letters of the English alphabet.
  • The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase.
  • Consonants comprise all letters that are not vowels.

Visualization

Tap to expand
Sort Vowels in a String INPUT String s = "lEetcOde" l E e t c O d e 0 1 2 3 4 5 6 7 Vowels (to sort) Consonants (fixed) Identified Vowels: ['E', 'e', 'O', 'e'] Positions: 1, 2, 5, 7 ASCII: 69, 101, 79, 101 ALGORITHM STEPS 1 Extract Vowels Collect all vowels from string ['E','e','O','e'] 2 Sort by ASCII Sort vowels ascending ['E','O','e','e'] E=69, O=79, e=101, e=101 3 Track Positions Note vowel indices positions: [1,2,5,7] 4 Replace In Order Put sorted vowels back pos[1] = 'E' pos[2] = 'O' pos[5] = 'e' pos[7] = 'e' FINAL RESULT Result t = "lEOtcede" l E O t c e d e 0 1 2 3 4 5 6 7 Verification: Consonants unchanged: l, t, c, d at 0, 3, 4, 6 OK Vowels sorted by ASCII: E(69) <= O(79) <= e(101) OK Output: "lEOtcede" Key Insight: The Two-Pass approach extracts vowels in the first pass, sorts them by ASCII value, then places them back in the second pass. Uppercase letters (A-Z: 65-90) have lower ASCII than lowercase (a-z: 97-122), so 'E'(69) comes before 'O'(79) before 'e'(101). Time: O(n log n), Space: O(n) for storing vowels. TutorialsPoint - Sort Vowels in a String | Two-Pass Optimized Approach
Asked in
Microsoft 25 Google 20 Amazon 18
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen