EasyNo. 0345

Reverse Vowels of a String — LeetCode 345 Python Solution

Topics
Two Pointers, String
On a study list
LeetCode 75
Reading time
3 min

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

PythonSolution
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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.