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)
Which of the following uses divide and conquer strategy?
Solution Implementation
Which algorithm should you use to find a node that is close to the root of the tree?
Recommended Readings
Patterns The Shortest Path Algorithm for Coding Interviews The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we can determine the
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Got a question? Ask the Monster 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.