Site icon vanitaai.com

LeetCode75: Reverse Vowels of a String

Introduction

The Reverse Vowels of a String problem is a popular string manipulation challenge that tests your ability to selectively modify characters within a string. Given a string s, the task is to reverse only the vowels—both lowercase (a, e, i, o, u) and uppercase (A, E, I, O, U)—while keeping all non-vowel characters in their original positions.

This problem strengthens your understanding of two-pointer techniques and character-based filtering. By learning how to identify vowels efficiently and swap them in place, you build a strong foundation for handling more complex string editing problems.

In this explanation, we’ll walk through an optimal and Pythonic approach to solve the Reverse Vowels of a String problem step-by-step along the way.

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints:

Python Solution

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set("aeiouAEIOU")
        s = list(s)
        i, j = 0, len(s) - 1

        while i < j:
            while i < j and s[i] not in vowels:
                i += 1
            while i < j and s[j] not in vowels:
                j -= 1

            # Swap vowels
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1

        return ''.join(s)

Step-by-Step Explanation

Step 1: Define Vowels Set

vowels = set("aeiouAEIOU")

Step 2: Convert String to List

s = list(s)

Step 3: Initialize Two Pointers

i, j = 0, len(s) - 1

Step 4: Find Next Vowel from Each End

while i < j and s[i] not in vowels:
    i += 1
while i < j and s[j] not in vowels:
    j -= 1

Step 5: Swap the Vowels

s[i], s[j] = s[j], s[i]
i += 1
j -= 1

Step 6: Return the Modified String

return ''.join(s)

Time and Space Complexity

This solution uses the two-pointer technique to efficiently reverse vowels in a string while maintaining the positions of all other characters.

Resources

Reverse Vowels of a String

LeetCode75 : Can Place Flowers

Exit mobile version