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: "AUOei"
💡 Note: All characters are vowels. Sort by ASCII: 'A'(65), 'O'(79), 'U'(85), 'e'(101), 'i'(105) → 'A', 'U', 'O', '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 StringConsonants stay in place, vowels get sorted by ASCIIInput:lEetcOdeconsonantvowelvowelconsonantconsonantvowelconsonantvowel↓ Extract and sort vowels: [E, e, O, e] → [E, O, e, e]Output:lEOtcedeResult: "lEOtcede"
Understanding the Visualization
1
Input Analysis
Identify consonants (stay fixed) and vowels (need sorting)
2
Sort Vowels
Extract vowels and sort by ASCII value
3
Rebuild String
Place sorted vowels back into vowel positions
Key Takeaway
🎯 Key Insight: Consonants act as anchors while vowels flow to their sorted positions
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