Reverse Vowels of a String - Problem
Reverse Vowels of a String
Given a string
The vowels are:
Example:
Input:
Output:
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.
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code