This is your mistake: if s[i] in v:
Simply change that to if s[i].lower() in vowels:
. Then it easily gets accepted where I assume you do it.
The problem is that v
can be large, making that check slow. For example for input s = 'a'*150000 + 'e'*150000
. Your v
will be the reverse, so every 'a'
will take long to be found in it, as the search goes through all those 'e'
. You take quadratic time and it should be linear.
Alternatively, prepare V = set(v)
between the loops and use if s[i] in V:
.
Bonus: a regex+slicing solution (fastest in my benchmark, fastest alternative I've found is ~27% slower):
def reverseVowels(self, s: str) -> str:
a = re.split('([aeiouAEIOU])', s)
a[1::2] = a[-2::-2]
return ''.join(a)