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 EvaluatorWhich of the following is a min heap?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job 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
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
Want a Structured Path to Master System Design Too? Donāt Miss This!