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

1def reverseVowels(self, s: str) -> str:
2    vowels = "aeiouAEIOU"
3    l, r = 0, len(s)-1
4    res = list(s)
5    while l < r:
6        if s[l] not in vowels:        # s[l] is not vowel
7            l += 1
8        elif s[r] not in vowels:      # s[r] is not vowel
9            r -= 1
10        else:
11            res[l], res[r] = res[r], res[l]   # both vowels, swap
12            l += 1
13            r -= 1
14    return "".join(res)
Not Sure What to Study? Take the 2-min Quiz to Find Your Missing Piece:

How many times is a tree node visited in a depth first search?

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

A heap is a ...?

Solution Implementation

Not Sure What to Study? Take the 2-min Quiz:

Which of the following is the prefix sum of array [1, 2, 3, 4, 5]?

Fast Track Your Learning with Our Quick Skills Quiz:

How would you design a stack which has a function min that returns the minimum element in the stack, in addition to push and pop? All push, pop, min should have running time O(1).


Recommended Readings


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫