Reverse Vowels of a String - Python Solution

1. Introduction

The "Reverse Vowels of a String" problem is an interesting twist on string manipulation. It involves reversing the order of all vowels in a given string, while keeping the rest of the characters intact. This problem tests one’s understanding of string handling, character identification, and two-pointer techniques in Python.

Problem

Given a string, the task is to reverse only the vowels present in it. Vowels are 'a', 'e', 'i', 'o', and 'u' (both lowercase and uppercase). Other characters in the string should remain in their original positions.

2. Solution Steps

1. Convert the string to a list to enable in-place modification.

2. Initialize two pointers: one at the start and the other at the end of the list.

3. Move the pointers towards each other, and when both pointers point to vowels, swap the vowels.

4. Continue this process until the pointers meet.

5. Convert the list back to a string and return it.

3. Code Program

def reverseVowels(s):
    vowels = set("aeiouAEIOU")
    s = list(s)
    i, j = 0, len(s) - 1

    while i < j:
        if s[i] not in vowels:
            i += 1
        elif s[j] not in vowels:
            j -= 1
        else:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1

    return ''.join(s)

# Example Usage
print(reverseVowels("hello"))  # Output: "holle"
print(reverseVowels("leetcode"))  # Output: "leotcede"

Output:

"holle"
"leotcede"

Explanation:

1. List Conversion: Converts the string to a list for easy modification.

2. Two-Pointer Technique: Uses two pointers to scan the string from both ends.

3. Vowel Checking: Swaps characters only when both pointers point to vowels.

4. Efficient Iteration: Continues until the pointers cross each other.

5. Reconversion to String: Converts the list back to a string before returning.

6. Time Complexity: The algorithm operates with O(n) time complexity, making it efficient for long strings.

7. Practical Use Case: Demonstrates a common pattern in string manipulation, useful in parsing and text processing applications.


Comments