Reverse Vowels of a String

Swap only the vowel characters using converging pointers that skip non-vowels.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
two-pointers string

Problem#

Reverse only the vowels (aeiouAEIOU) of a string, leaving consonants in place.

Examples#

  • "hello""holle"
  • "leetcode""leotcede"
  • "aA""Aa"

Constraints#

  • 1 <= s.length <= 3 * 10^5, printable ASCII.

Approach#

Converging two pointers. Each side independently advances past non-vowels; when both point at vowels, swap and step inward.

Solution#

Reverse Vowels
class Solution {
public:
string reverseVowels(string s) {
auto isVowel = [](char c) {
c = tolower((unsigned char)c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
int l = 0, r = s.size() - 1;
while (l < r) {
while (l < r && !isVowel(s[l])) ++l;
while (l < r && !isVowel(s[r])) --r;
if (l < r) swap(s[l++], s[r--]);
}
return s;
}
};

Editorial#

This is the “skip-junk converging pointer” template used for valid palindrome. The lowercase normalization in isVowel lets us handle both cases without branching.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.