Solving Leetcode Interviews in Seconds with AI: Reverse Vowels of a String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "345" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: s = "IceCreAm" Output: "AceCreIm" Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm". Example 2: Input: s = "leetcode" Output: "leotcede" Constraints: 1 <= s.length <= 3 * 105 s consist of printable ASCII characters.
Explanation
Here's the breakdown of the solution:
- Two-Pointer Approach: Use two pointers, one starting from the beginning of the string and the other from the end. Move the pointers towards each other until they meet.
- Vowel Identification: At each pointer position, check if the character is a vowel (case-insensitive). If not, move the pointer accordingly.
Swap Vowels: If both pointers point to vowels, swap the characters at those positions and move both pointers.
Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(n), because the given string is immutable in Python, and we have to convert it to a list of chars.
Code
def reverseVowels(s: str) -> str:
"""
Reverses only the vowels in a given string.
Args:
s: The input string.
Returns:
The string with vowels reversed.
"""
vowels = "aeiouAEIOU"
s_list = list(s) # Convert string to a list of characters
left, right = 0, len(s) - 1
while left < right:
while left < right and s_list[left] not in vowels:
left += 1
while left < right and s_list[right] not in vowels:
right -= 1
if left < right:
s_list[left], s_list[right] = s_list[right], s_list[left]
left += 1
right -= 1
return "".join(s_list) # Convert list back to string