Minimum Swaps to Group All 1's Together

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 = "hello"
Output: "holle"

Example 2:

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

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

Solution

We will implement two pointers in opposite directions and swap the vowels pointed by the two pointers. We will start at the two ends of the string s and move our way into the middle. In each while loop iteration we will check whether s[l] or s[r] is a vowel. If both of them are vowels, then we swap the two characters. If not, we will update l or r towards the middle by shifting 1 index.

Notice that in the following implementation, we first update l until s[l] is a vowel, then proceed to finding s[r] to be a vowel - this spans over many iterations. It is also correct to use while (instead of if-else) to find the vowels' positions for both pointers, but we will need to check l < r before swapping (check Valid Palindrome for an implementation example).

Implementation

def reverseVowels(self, s: str) -> str:
    vowels = "aeiouAEIOU"
    l, r = 0, len(s)-1
    res = list(s)
    while l < r:
        if s[l] not in vowels:        # s[l] is not vowel
            l += 1
        elif s[r] not in vowels:      # s[r] is not vowel
            r -= 1
        else:
            res[l], res[r] = res[r], res[l]   # both vowels, swap
            l += 1
            r -= 1
    return "".join(res)

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which of the following is a good use case for backtracking?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!