#345
Reverse Vowels of a String
EasyTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses the two-pointer technique to reverse the vowels in a single pass through the string. This is efficient because we only traverse the string once, making it faster.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one at the start and one at the end of the string.
- 2Step 2: Move the left pointer to the right until a vowel is found.
- 3Step 3: Move the right pointer to the left until a vowel is found.
- 4Step 4: Swap the vowels at the two pointers and move both pointers towards the center.
- 5Step 5: Repeat until the pointers meet.
solution.py15 lines
1# Full working Python code
2
3def reverseVowels(s):
4 s_list = list(s)
5 left, right = 0, len(s) - 1
6 vowels = set('aeiouAEIOU')
7 while left < right:
8 while left < right and s_list[left] not in vowels:
9 left += 1
10 while left < right and s_list[right] not in vowels:
11 right -= 1
12 s_list[left], s_list[right] = s_list[right], s_list[left]
13 left += 1
14 right -= 1
15 return ''.join(s_list)ℹ
Complexity note: The time complexity is O(n) because we traverse the string only once, and the space complexity is O(1) as we are not using any additional data structures that grow with input size.
- 1Using two pointers can significantly reduce time complexity.
- 2Understanding vowel identification is crucial for the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.