InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Reverse Vowels of a String

easy Original ↗ 00:00

Problem

Given a string s, reverse the order of only its vowels and return the result. Every consonant (and any other character) stays exactly where it is; the vowels swap positions among themselves so that the first vowel trades places with the last, the second with the second-to-last, and so on.

Vowels are a, e, i, o, u in both lowercase and uppercase. The string may contain letters and printable ASCII characters.

Examples

  • s = "hello""holle" Vowels are e (index 1) and o (index 4); they swap, consonants h,l,l stay put.
  • s = "leetcode""leotcede" Vowel sequence e,e,o,e reverses to e,o,e,e in the same four slots.
  • s = "aA""Aa" Both characters are vowels, so they swap; each keeps its own case.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of printable ASCII characters.
  • Expected O(n) time — with 3 * 10^5 characters, anything quadratic is too slow.

Think about it first

Hint 1 Only the vowels move, and they land exactly in the slots vowels already occupy — the set of vowel *positions* is unchanged, only which vowel sits where.
Hint 2 Think of how you'd reverse a whole array with two pointers converging from the ends. What should a pointer do when it's sitting on a consonant?
Hint 3 Walk `left` rightward until it hits a vowel and `right` leftward until it hits a vowel; swap them, step both inward, repeat until the pointers cross. Strings are immutable in Python, so do it on `list(s)` and join at the end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug