Reverse Vowels of a String - Problem

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Input & Output

Example 1 — Basic Case
$ Input: s = "hello"
Output: "holle"
💡 Note: The vowels are 'e' and 'o'. After reversing them, we get 'o' and 'e', resulting in "holle"
Example 2 — Mixed Case Vowels
$ Input: s = "leetcode"
Output: "leotcede"
💡 Note: The vowels are 'e', 'e', 'o', 'e'. After reversing: 'e', 'o', 'e', 'e', resulting in "leotcede"
Example 3 — Single Vowel
$ Input: s = "aA"
Output: "Aa"
💡 Note: Two vowels 'a' and 'A'. After reversing positions, we get "Aa"

Constraints

  • 1 ≤ s.length ≤ 3 × 105
  • s consists of printable ASCII characters

Visualization

Tap to expand
Reverse Vowels of a String INPUT String: "hello" h 0 e 1 l 2 l 3 o 4 = Vowel Vowels: a, e, i, o, u (both cases) Two Pointers: left = 0, right = 4 Find vowels from both ends ALGORITHM STEPS 1 Initialize Pointers left=0, right=len-1 2 Find Left Vowel Move left until vowel found 3 Find Right Vowel Move right until vowel found 4 Swap Vowels Exchange and move both Swap: e <--> o Before: "h[e]ll[o]" After: "h[o]ll[e]" Repeat until left >= right FINAL RESULT Output: "holle" h o l l e swapped OK - Verified! Vowels reversed Complexity: Time: O(n) Space: O(n) (for char array conversion) Key Insight: The two-pointer technique efficiently finds vowels from both ends simultaneously. By swapping in-place as we find matching pairs, we achieve O(n) time with a single pass. TutorialsPoint - Reverse Vowels of a String | Optimal Two-Pointer Approach
Asked in
Microsoft 35 Amazon 25 Facebook 20
85.0K Views
Medium Frequency
~15 min Avg. Time
2.2K 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