↓Skip to main content
  1. LeetCode/

LeetCode 345: Reverse Vowels of a String

·1 min· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted ×3

Approach
#

Two pointers each skip non-vowels and swap when both point at vowels (Two Pointers Template 1). Vowels include uppercase, so test against the set "aeiouAEIOU".

My Solution
#

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

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Uppercase vowels count too.

Interview Explanation
#

Two pointers skip non-vowels and swap when both are vowels, then move inward. Time O(n).

Related

LeetCode 344: Reverse String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 344 note: swap with two pointers and move inward to reverse in place
LeetCode 392: Is Subsequence
·2 mins
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 note: two pointers; the pointer on t always advances, and the one on s advances on a match; bound-check both
LeetCode 125: Valid Palindrome
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 125 note: two pointers skip non-alphanumeric characters and compare lowercase letters, with digits included
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side