Reverse Vowels of a String - Problem
Reverse Vowels of a String

Given a string s, your task is to reverse only the vowels in the string while keeping all other characters in their original positions. Return the modified string.

The vowels are: 'a', 'e', 'i', 'o', 'u' and they can appear in both lowercase and uppercase, and may appear multiple times in the string.

Example:
Input: "hello"
Output: "holle"
Explanation: The vowels 'e' and 'o' are swapped while 'h', 'l', 'l' stay in place.

Goal: Implement an efficient algorithm to swap vowels while preserving the original structure of the string.

Input & Output

example_1.py โ€” Basic Example
$ Input: s = "hello"
โ€บ Output: "holle"
๐Ÿ’ก Note: The vowels in 'hello' are 'e' and 'o'. When reversed, 'e' goes to position 4 and 'o' goes to position 1, resulting in 'holle'.
example_2.py โ€” Mixed Case
$ Input: s = "leetcode"
โ€บ Output: "leotcede"
๐Ÿ’ก Note: The vowels are 'e', 'e', 'o', 'e'. When reversed: 'e', 'o', 'e', 'e'. Result: 'leotcede'.
example_3.py โ€” Edge Case
$ Input: s = "aA"
โ€บ Output: "Aa"
๐Ÿ’ก Note: Both characters are vowels ('a' and 'A'). When reversed, 'A' comes first and 'a' comes second.

Constraints

  • 1 โ‰ค s.length โ‰ค 3 ร— 105
  • s consists of printable ASCII characters
  • The vowels are 'a', 'e', 'i', 'o', 'u' in both lowercase and uppercase

Visualization

Tap to expand
Musical Chairs with VowelsRow of Chairs (String Characters)hellowStep 1: Place OrganizersLRStep 2: Find Red Chairs (Vowels)LRStep 3: Swap People in Red ChairsoeSWAP!๐ŸŽฏ Result: Only vowels (red chairs) changed positions!
Understanding the Visualization
1
Setup
Place two organizers at opposite ends of the row
2
Find
Each organizer walks toward center until they find a red chair
3
Swap
The people in the red chairs swap positions
4
Continue
Organizers move past swapped chairs and repeat
Key Takeaway
๐ŸŽฏ Key Insight: Two pointers efficiently swap elements from opposite ends without needing extra space, making this the optimal O(n) time, O(1) space solution.
Asked in
Google 23 Amazon 18 Microsoft 15 Apple 12
142.4K Views
Medium Frequency
~15 min Avg. Time
2.8K 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