Reverse Vowels of a String — LeetCode 345 Python Solution
- Problem
- #345
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Python solution
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = "aeiouAEIOU"
i, j = 0, len(s) - 1
cs = list(s)
while i < j:
while i < j and cs[i] not in vowels:
i += 1
while i < j and cs[j] not in vowels:
j -= 1
if i < j:
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j - 1
return "".join(cs)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(|\Sigma|), where \Sigma is the size of the character set auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 345. Reverse Vowels of a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 345. Reverse Vowels of a String?
- LeetCode 345. Reverse Vowels of a String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 345. Reverse Vowels of a String?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 345. Reverse Vowels of a String?
- The Python solution on this page uses O(|\Sigma|), where \Sigma is the size of the character set auxiliary space.
- What topics does LeetCode 345. Reverse Vowels of a String cover?
- LeetCode 345. Reverse Vowels of a String is tagged Two Pointers and String on LeetCode.