345. Reverse Vowels of a String

Solution:

  • strings are immutable in python so I had to convert the string into a list, returning the joined list for the solution.
  • first try I converted to string to an array, used two pointers to loop from left and from right and switched the vowels from left to right.
  • I thought maybe I could save the space complexity by not making a separate list, and instead create the solution string on the fly. But since strings are immutable, this wouldn’t work. Appending strings would result in a far greater time complexity.
class Solution:
    def reverseVowels(self, s: str) -> str:

        def isVowel(c):
            if c in 'aeiouAEIOU':
                return True
            return False

        l = 0
        r = len(s)-1
        sarr = list(s)
        while l < r:
            while l < len(sarr) and l < r and not isVowel(sarr[l]):
                l += 1
            while r >= 0 and l < r and not isVowel(sarr[r]):
                r -= 1
            sarr[l], sarr[r] = sarr[r], sarr[l]
            l += 1
            r -= 1
        return "".join(sarr)

A little more efficient by putting the vowels in a set and not a string.

class Solution:
    def reverseVowels(self, s: str) -> str:
        l = 0
        r = len(s)-1
        sarr = list(s)
        vowels = set('aeiouAEIOU')
        while l < r:
            while l < r and sarr[l] not in vowels:
                l += 1
            while l < r and sarr[r] not in vowels:
                r -= 1
            sarr[l], sarr[r] = sarr[r], sarr[l]
            l += 1
            r -= 1
        return "".join(sarr)