Sort Vowels in a String - Problem

Given a string s, you need to create a new string where all consonants stay in their original positions but all vowels are sorted by their ASCII values.

Think of it like organizing a library: the shelves (consonant positions) stay fixed, but you rearrange the books (vowels) in alphabetical order within those shelves.

The Rules:

  • ๐Ÿ”’ Consonants must remain in their exact original positions
  • ๐Ÿ“ Vowels (a, e, i, o, u - both lowercase and uppercase) should be sorted by ASCII value
  • ๐ŸŽฏ ASCII sorting means: A < E < I < O < U < a < e < i < o < u

Example: "lEetcOde" โ†’ "lEOtcede"
Vowels found: [E, e, O, e] โ†’ Sorted: [E, O, e, e]
Place them back: lE*tcOde โ†’ lE*tcede

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "lEetcOde"
โ€บ Output: "lEOtcede"
๐Ÿ’ก Note: The vowels are [E, e, O, e]. After sorting by ASCII: [E, O, e, e]. Placing them back: l(E)*(O)tc(e)d(e) = "lEOtcede". Consonants l, t, c, d stay in their original positions.
example_2.py โ€” Mixed Case
$ Input: s = "lYmpH"
โ€บ Output: "lYmpH"
๐Ÿ’ก Note: No vowels found in the string (Y is not considered a vowel in this problem). The string remains unchanged since only consonants are present.
example_3.py โ€” All Vowels
$ Input: s = "AeIoU"
โ€บ Output: "AeIoU"
๐Ÿ’ก Note: All characters are vowels: [A, e, I, o, U]. After ASCII sorting: [A, I, U, e, o]. Result: "AIUeo". Wait, that's wrong... Let me recalculate: ASCII values: A(65), I(73), U(85), e(101), o(111). So sorted: A, I, U, e, o โ†’ "AIUeo"

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists only of letters (both uppercase and lowercase)
  • Vowels are: a, e, i, o, u, A, E, I, O, U
  • All other letters are considered consonants

Visualization

Tap to expand
Visual Process: Sort Vowels in StringOriginal: "lEetcOde"lEetcOdeVowel positions: 1, 2, 5, 7Extracted vowels: [E, e, O, e]EeOeASCII: E(69), O(79), e(101)After sorting: [E, O, e, e]EOeeSorted by ASCII valueReplace vowels: "lEOtcede"lEOtcedeConsonants preserved, vowels sorted!๐ŸŽฏ Key Insight: Two passes - extract & sort, then replace in order
Understanding the Visualization
1
Identify Positions
Mark vowel positions (red) and consonant positions (blue) in the original string
2
Extract & Sort
Remove all vowels and sort them by ASCII values: A-Z comes before a-z
3
Replace in Order
Put sorted vowels back into vowel positions sequentially
4
Final Result
Consonants unchanged, vowels properly sorted by ASCII values
Key Takeaway
๐ŸŽฏ Key Insight: The two-pass approach is optimal - first collect and sort all vowels, then place them back sequentially in vowel positions while preserving consonant positions.
Asked in
Amazon 45 Google 38 Microsoft 29 Meta 22
42.3K Views
Medium Frequency
~15 min Avg. Time
1.9K 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