Skip to content

Commit a4724fb

Browse files
⚡️ Speed up method Solution.reverseVowels by 15%
1 parent d0e6284 commit a4724fb

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

codeflash/test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
_vowels = set("aeiouAEIOU") # noqa: RUF012
3+
4+
def reverseVowels(self, s: str) -> str:
5+
left, right = 0, len(s) - 1
6+
chars = list(s)
7+
vowels = self._vowels # Local variable for faster lookup
8+
9+
while left < right:
10+
# Advance left pointer to next vowel
11+
while left < right and chars[left] not in vowels:
12+
left += 1
13+
# Advance right pointer to previous vowel
14+
while left < right and chars[right] not in vowels:
15+
right -= 1
16+
if left < right:
17+
chars[left], chars[right] = chars[right], chars[left]
18+
left += 1
19+
right -= 1
20+
21+
return "".join(chars)

0 commit comments

Comments
 (0)