345. Reverse Vowels of a String

#string #array #two-pointers

In a string s, reverse all the vowels in the string and return it.

Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

Intuition

  • we can swap the vowels in the front and back

Approach

  • use two pointer to track the vowel at the front and back

  • if both point to a vowel swap them

  • continue till the front and back pointer meet

Complexity

Space Complexity
Time Complexity

O(n)\text{O}(n)

O(n)\text{O}(n)

  • extra storage is used to store the string converted to char array

  • we iterate over the array only once

Code

Last updated