EasyNo. 0345
Reverse Vowels of a String — LeetCode 345 Python Solution
- Pattern
- Two Pointers
- Topics
- Two Pointers, String
- On a study list
- LeetCode 75
- 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
- Time
- O(n), where n is the length of the string
- Space · auxiliary
- O(|Σ|), where Σ is the size of the character set
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
| No. | Problem | Difficulty |
|---|---|---|
| 0344 | Reverse String | Easy |
| 0005 | Longest Palindromic Substring | Medium |
| 0028 | Find the Index of the First Occurrence in a String | Easy |
| 0125 | Valid Palindrome | Easy |
| 0151 | Reverse Words in a String | Medium |
| 0165 | Compare Version Numbers | Medium |
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(|Σ|), 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.