Skip to content
Problem 345 · LeetCode 345(opens in a new tab)

Reverse Vowels of a String

EasyStrings

You are given a string s. Reverse the order of its vowels and leave every other character where it is, then return the new string.

A vowel here means one of a, e, i, o, u, written in lower or upper case. A vowel keeps its own case when it moves; y is not a vowel.

Example 1

Input:  s = "Tunafish"
Output: "Tinafush"
Why:    the vowels u, a, i come back as i, a, u
2 more examples and the constraints

Example 2

Input:  s = "AbcdE"
Output: "EbcdA"
Why:    upper-case vowels count and keep their case

Example 3

Input:  s = "rhythm"
Output: "rhythm"
Why:    no vowels, so nothing moves

Constraints

  • 1 ≤ length of s ≤ 300,000
  • s holds printable ASCII characters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Collect, then refillO(n)
  2. Two pointersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 300,000 charactersVerdict
Collect, then refillO(n)
Passes; two passes and a vowel list
Two pointersO(n)
Best; one pass, swaps in place

n = length of s. Both are linear; the two-pointer version reads each character once.

Edge cases to test

  • No vowels. "rhythm" comes back unchanged; i walks right until it meets j.
  • Upper case. A, E, I, O, U are vowels too, and each keeps its case: "AbcdE" gives "EbcdA".
  • An odd number of vowels. The middle vowel is its own partner and stays where it is.
  • Symbols and spaces. They are never vowels, so they never move: "hi, you!" gives "hu, yoi!".

Common mistakes

  • Checking only lower-case vowels, which leaves capitals like A in place.
  • Moving both pointers on every step, which skips a vowel when only one side has found one.
  • Counting y as a vowel.

How to talk through it

  1. 1Clarify. Which letters are vowels? Do capitals count, and is y one? Can there be symbols?
  2. 2Start simple. Collect the vowels, then refill the vowel slots from the end of the list. That is O(n) already.
  3. 3Tighten to one pass. Pair the first vowel with the last using two pointers that each skip non-vowels.
  4. 4State the cost. Each pointer moves one way, so O(n) time; only a copy of the string for space.
  5. 5Test out loud. Run a string with no vowels, one with capitals, and one with an odd number of vowels.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?