pythonperformancetime-complexityruntime-errordata-analysis

How can i improve my python code of leetcode problem 345 and how i can i improve the time complexity


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 = "IceCreAm"

Output: "AceCreIm"

Explanation:

The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a', 'A', 'e', 'E', 'i', 'I', 'O', 'o', 'U','u']
        found = []
        location = []
        for i in range(len(s)):
            if s[i] in vowels:
                found.append(s[i])
                location.append(i)
        location.reverse()
        r2 = []
        for i in range(len(s)):
            if i in location:
                r2.append(found[location.index(i)])
            else: r2.append(s[i])
        s = ''.join(r2)
        return(s)

This code passes all test cases except the last one (479/480 test cases passed) the last one is very large but i have attached it below.

image of the runtime error saying it takes too long.

how can i improve the time complexity of my code and how can i make it faster? https://www.mashupstack.com/share/67cd359de9836


Solution

  • You can solve it using two pointers; which is a typical O(N) approach to solve such problems:

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