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.
- Collect, then refillO(n)
- Two pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 300,000 characters | Verdict |
|---|---|---|---|
| Collect, then refill | O(n) | Passes; two passes and a vowel list | |
| Two pointers | O(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;
iwalks right until it meetsj. - Upper case.
A,E,I,O,Uare 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
Ain place. - Moving both pointers on every step, which skips a vowel when only one side has found one.
- Counting
yas a vowel.
How to talk through it
- 1Clarify. Which letters are vowels? Do capitals count, and is
yone? Can there be symbols? - 2Start simple. Collect the vowels, then refill the vowel slots from the end of the list. That is O(n) already.
- 3Tighten to one pass. Pair the first vowel with the last using two pointers that each skip non-vowels.
- 4State the cost. Each pointer moves one way, so O(n) time; only a copy of the string for space.
- 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?